Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

'for' internals 2

Status
Not open for further replies.

ktulu2

Technical User
Jan 16, 2003
11
US
Can anyone help me understand what is going on in this situation?
Code:
$a = 1;
$b = 2;
$c = 3;
print "$a $b $c\n";

for ($a, $b, $c){
    $_++;
}

print "$a $b $c"

Output:
1 2 3
2 3 4

When I originally wrote this I thought that Perl might store a reference to each variable in $_ so I used $$_++ instead, which only gave me an error ("Modification of read only value"). Then for some reason I removed the extra $ and it it gave me the result I was hoping for. But I still don't understand why this works. I guess what I am asking is why does modifying $_ effect the other variables in the same manner? Can anyone give me some insight?

Thanks

+Cory
 
Well Cory, the reason that your variables get modified is that 'for' is synonymous with 'foreach' in perl. They are the exact same construct.

When you use commas instead of semicolons to delimit your for variables, you are telling the perl interpreter to treat the contents as a list instead of as an initializer, condition, and modifyer.

What you were actually doing is iterating over a list:

foreach my $thingy ($a, $b, $c){
$thingy++;
}

The list consisted of $a $b and $c.
$_ is the default list iterator if none is specified (which you didn't).

That's the reason why modifying $_ altered the contents of $a, $b and $c, that's the normal supported behavior for a list iterator.

HTH
--Jeremiah

Gratuitous plug:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top