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:
foreach my $line (@text){ chomp($line); next if($line =~ /^\s*#/); #...do something with the non-commented lines }
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: I should've known better!
by TimToady (Parson) on Sep 11, 2009 at 02:26 UTC | |
by GrandFather (Saint) on Sep 11, 2009 at 03:01 UTC | |
by moritz (Cardinal) on Sep 14, 2009 at 14:16 UTC | |
|
Re: I should've known better!
by vitoco (Hermit) on Sep 10, 2009 at 22:32 UTC | |
|
Re: I should've known better!
by Zen (Deacon) on Sep 14, 2009 at 14:04 UTC |