good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
A wise monk once advised me to avoid assigning directly to $_.
He counseled me that Perl uses $_ in a variety of ways that fledgelings such as myself may not understand. When through youthful exuberance we blow away the existing values stored in $_ we create problems for ourselves later. For instance, what if the code you are writing is inside a loop which already uses $_ for something else? For instance:
All of a sudden your first way of doing it, which assigns to $_, breaks the existing program so that it no longer prints out all of the lines in a file. "Does the second loop give you nasty C flashbacks?" I would argue that we are programming in Perl. We are not programming in "Not-C". The second method is perfectly proper Perl and is preferable for those of us who are concerned about modifying $_ in a way which may interfere with other parts of a program. Update: japhy informs me below that for(split ' '){} inside a while (<FH>){} creates a local copy of $_ and does not use the same one that the while() uses. Hence, the use of the first method does not break the program I posted. Since posting the above I have also noticed that LW, Merlyn et al in the Camel book sometimes assign directly to $_. For example, on page 103 of the second edition they say:
One ought not to be more Catholic than the Pope. If LW and Merlyn think that assigning to $_ is safe and proper Perl style then so be it. </code> In reply to Re: What would you do?
by sierrathedog04
|
|