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:
while (<MYFILEHANDLE>){ ...your code here... print; }
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:
while (<>) { chomp; if (s/\\$//) { $_ .= <>; redo; } # now process $_ }
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
in thread What would you do?
by MeowChow
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |