From: Ahmed Moustafa <[EMAIL PROTECTED]> > Elaine -Hfb- Ashton wrote: > > I always found the local, my, our mess pretty confusing and the best > > explanation is MJD's "Coping with Scoping" > > > > http://perl.plover.com/FAQs/Namespaces.html > > > > Make good note of the text in red :) > > Elaine, thanks a lot for MJD's article. There is a great difference > before reading it and after :) > > In the example: > > <code> > { my $seed = 1; > sub my_rand { > $seed = int(($seed * 1103515245 + 12345) / 65536) % 32768; > return $seed; > } > } > </code> > > , the function my_rand () is declared inside a block. Does that mean a > function can be declared anywhere in the program (i.e. inside another > function, loop or if block)?
Yes. But you should be carefull with this! For example if you write this: for (1..10) { my $x = $_; sub foo { print $x,"\n"; } foo; } foo; Or sub bar { my $x = shift; sub foo { print "$x\n"; } } bar 1; foo; bar 2; foo; what would you think you will get? Try it and play with it some more! As you can see the function keeps a reference to the very first instance of $x. The $x variable doesn't stay shared between foo() and bar(). This means that you should NOT create named subroutines in any loops or bodies of other functions. Unnamed functions are different beasts though. sub MakeFoo { my $x = shift; return sub {print $x,"\n"} } $foo1 = MakeFoo 1; $foo2 = MakeFoo 2; $foo1->(); $foo2->(); In this case you are creating a new "function" each time. (Actually what you create in this case is called closure.) Jenda =========== [EMAIL PROTECTED] == http://Jenda.Krynicky.cz ========== There is a reason for living. There must be. I've seen it somewhere. It's just that in the mess on my table ... and in my brain I can't find it. --- me -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]