Syntactic Confectionery Delight | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
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:
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.
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...:
In reply to Perlplexation - foreach shoulda Known by raybies
|
|