Perl foreach loop aliasing behavior
November 15, 2010 21:54:19 Last update: November 15, 2010 21:54:19
In the Perl for (foreach) loop, the looping variable is actually an alias (reference) to the original variable. Therefore, any changes applied to that variable are reflected in the original variable:
This trick can be used to trim a Perl string:
C:\>perl @a = ('1', '2', '3'); for my $i (@a) { $i =~ s/$/Ha!/; } print join ', ', @a; ^Z 1Ha!, 2Ha!, 3Ha!
This trick can be used to trim a Perl string:
C:\>perl $s = ' abcd '; for ($s){ s/^\s+//; s/\s+$//; } print "'$s'"; ^Z 'abcd'