
BillKSmith
Veteran
Nov 4, 2010, 9:24 PM
Post #5 of 5
(453 views)
|
use strict; use warnings; use Data::Dumper; my @array = ( 0 .. 99 ); my $counter = 'This is never use'; foreach $counter (@array) { # $_ = $counter; # print 'the first $_ is: ' . $_ . "\n"; $counter++; # print 'the first $counter is: ' . $counter . "\n"; } print Dumper( \@array, $counter ); This is your first loop without the prints or the assignment to $_. (Put it back in if you wish, it does not change anything) The initial value of $counter was changed to emphasise that it is not used. Run this code. Every array element is incremented by one. $counter is unchanged. Contrary to what you would expect, the $counter inside the loop is a seperate variable. Each time through the loop, it is an alias for a different array element. Each time that $counter++ is executed, a diffferent array element is incremented. $_ has not special role in this code. It is a global variable. Now that you have seen this, please reread the 'FOREACH LOOP' section of perldoc perlsyn. It explains it better than either of us has. Good Luck, Bill
(This post was edited by BillKSmith on Nov 5, 2010, 6:13 AM)
|