Jon Forsyth <[email protected]> asked:
> I am truly a beginner. Could someone help me understand this syntax
> out of a code example from "Learning Perl"? On line 5 I'm confused
> as to why "my $number" is between "foreach" and the ()? is "my
> $number part of the loop?
"my" declares a variable for the lexical scope. While Perl by itself will
happily let variables spring into existence whenever you first refer to them,
the accepted best practice is to run perl with the -w switch or the "use
warnings;" pragma which requires variables to be declared before their first
use.
The "foreach" loop iterates over each element in the argument list passed
between the (). Unless there's a variable name between the keyword foreach and
the braces, foreach makes the default variable $_ to an alias for each of the
elements in the argument list. If there's a variable between "foreach" and the
braces, that variable becomes the alias instead.
Please note that I said alias instead of copy - if you modify $_ or your loop
variable, it'll change the contents of your array:
#!/usr/bin/perl -w
my @array = qw(foo baz bar);
print join(',',@array), "\n";
foreach (@array){
$_ = uc($_);
}
print join(',',@array), "\n";
__END__
HTH,
Thomas
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/