[Athens-pm] Perl oddities

Giorgos Epitidios gepiti at internet.gr
Thu Nov 14 00:37:53 CST 2002


Good morning everybody. Yesterday I spoke about not being able to have one
foreach loop inside another. That was wrong.  What you cannot do is play
with the $_ variable inside a loop (if you want to keep your array elements
intact). See the following example:

sub func {
   $_ = 100;
}


my @array = (1,2,3);

print "before calling func\n";
foreach ( @array ) {
   print "$_\n";
}
print "calling func inside loop\n";
foreach ( @array ) {
   print "$_\n";
   func;
}
print "after calling func\n";
foreach ( @array ) {
   print "$_\n";
}

What you get by running it is:

before calling func
1
2
3
calling func inside loop
1
2
3
after calling func
100
100
100

As someone mentioned in the comp.lang.perl forum:

 Little known features of foreach.  The iteration variable used
 in the foreach is not a copy, but in fact an alias to the value,
 in this case $_.  Thus, when you change it you change the value
 in the array.

So actually $_ IS each element of the array. This means that &func changes
the array elements.

Hope that is of interest to someone.


Giorgos Epitidios

P.S. My mistakes make me wiser





More information about the Athens-pm mailing list