Learned something new yesterday that's such a basic construct of Perl that I'm embarrassed to admit it, but in case someone else out there needs a refresher or didn't know this, here goes:
The foreach (and for and map, etc) command can be used to modify the list that it is iterating over. I know. I should've known this. I don't know how many times I've wanted to modify an array and had to create my own index because I didn't realize that if I had something like:
my @x = (1..10); foreach (@x) { $_ += 100; } print "@x"; OUTPUT: 101 102 103 104 105 106 107 108 109 110
I guess I just assumed it didn't because when you declare the variable in a foreach loop, you don't think of it as a reference (because it really isn't one, but it sorta acts like one in that it represents the actual element in the list.) I had always figured that $_ was simply a copy of what was in the array, not the actual element. But apparently Perl is cooler than that. ;)
SO in this example: $element can be modified in the array.
my @x = (1..10); foreach my $element (@x) { $element += 100; } print "@x"; OUTPUT: 101 102 103 104 105 106 107 108 109 110
Anyhow, the discovery was a delighful suprise, that I came across while preparing to brief a bunch of nonPerl users on Perl. This presentation's been a great way to really fill in the many cracks I have about my understanding of basic Perl programming. (I'm up to about 60 Power point slides... poor suckers attending this meeting are going to slip into a comma... death by Powerpoint! Buwahahaha)
I also tested these loops constructs and observed they altered the loop array elements in the same way...:
map {$_ += 100} @x; (yields same output and alters @x as does...) $_ += 100 for @x; in case you wondered... :)
In reply to Perlplexation - foreach shoulda Known by raybies
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |