Keep It Simple, Stupid | |
PerlMonks |
I should've known better!by ack (Deacon) |
on Sep 10, 2009 at 18:03 UTC ( [id://794638]=perlmeditation: print w/replies, xml ) | Need Help?? |
Well, I am red-faced with embarassment. Having worked around Perl for several years, I found one of those "traps" that must frustrate "newbies" but that I should've seen coming given my time with Perl. A construct that I (and I suspect otheres) have used is the following:
The surprise was not in the basic construct, but rather that I forgot that $line is just an alias for each of the actual elements in the array @text. Of course the array could be anything (doesn't have to be text) and the processing in the loop could be anything. The important thing is that anything (e.g., chomp($line) in this case) that alters the loop variable (e.g., $line) is actually operating on and affecting the actual values in the array. Plenty of documentation reminds (and even warns us) of that fact...but I am almost continually forgetting it. I am amazed that this doesn't bit me more frequently...maybe if it did, I'd do a better job of remembering it...he says with a wry grin. It just now bit me on a little test case I had quickly coded up as I looked at one of the Q&A's about 'arrays' when I went to print out the value of @text after processing it in the above loop and then push()'ing the result into an ouput array which I then went on to print out for comparison. Much to my dismay, when I printed out @text after the loop I found that all of the new-lines were gone! I had to stop and fret over it and then I remembered! In chomp()'ing the loop variable, I was actually chomping the array's member! Duhhh! Well, color me 'embarassed'! I think it is really powerful that the loop variable is an alias and I have actually used that to good advantage in several instnaces. But it must be really mysterious to those new to Perl that using common constructs like the comment-removal code I showed above can result in some pretty mysterious behavior. Just an observation regarding the power and, sometimes, mystery of Perl.
ack
Albuquerque, NM
Back to
Meditations
|
|