[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] $_ global?



At 16.50 97/2/13, Terry Lynch wrote:
>Here is some code that seems to show '$_' as a local variable:
>------------------------------
>$_ = "Am I global?";
>print "$_\n";
>@marbles = ('red','orange','yellow','green','blue','indigo','violet');
>foreach (@marbles) {print "$_\n";}
>print "$_\n";
>------------------------------
>
>And here are the results:
>------------------------------
>Am I global?
>red
>orange
>yellow
>green
>blue
>indigo
>violet
>Am I global?
>------------------------------

This has to do with the particulars of foreach; "(In a foreach loop) the
variable is implicitly local to the loop and regains its former value upon
exiting the loop" (perlsyn manpage).  This is out of necessity; you are
iterating through a list, and VAR is the name of the thingy each time
through.  No matter what global variable you have, it is going to work the
same way:

$x = "Am I global?";
print "$x\n";
@marbles = ('red','orange','yellow','green','blue','indigo','violet');
foreach $x (@marbles) {print "$x\n";}
print "$x\n";

This is exactly the same code, except that in your example, $_ is implicit
in the foreach statement, while here $x is explicit.

Hope that helps,

#================================================================
Chris Nandor                                      pudge@pobox.com
PGP Key 1024/B76E72AD                           http://pudge.net/
Keyfingerprint = 08 24 09 0B CE 73 CA 10  1F F7 7F 13 81 80 B6 B6