Today, I stumbled over something in Perl I was not aware of: it "localizes" the variable that the elements of the list iterated over is assigned to.
This, of course, is documented in the Perl documentation - however I failed to remember or read it.
The following script demonstrates what I mean:
use warnings;
use strict;
my $g = 99;
foreach $g (1..5) {
p($g);
}
sub p {
my $l = shift;
printf ("%2d %2d\n", $g, $l);
}
The script prints
99 1
99 2
99 3
99 4
99 5
because $g
is "localized" to the foreach
loop.
As far as I can tell there is no difference if I had added my
to $g
in the foreach loop:
foreach my $g (1..5) {
Actually, I ended up doing it because I feel it makes it clearer that the variable is local to the loop.
My question is now: is there a scenario where my using my
does make a difference (given that $g
is already declared globally).
$g
I will go and research this a bit. – Epiphyte