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:

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.