In being tasked with modifying an ancient parser I soon noticed that it was using local $/=undef. Which I gathered is generally frowned upon.

It is not. It is frowned upon if it is used in a nonsensical way, like in the code snippet you posted.

Used at toplevel local has no effect, since there is no outer scope: you could just as well modify the global $/ instead. And if readline (or the diamond operator <>) isn't, but sysread used instead, setting $/ doesn't do anything useful.

sysread reads bytes. A subsequent chomp on the result only removes $/ (in your case: nothing, since $/ is undef) if $/ happens to be at the end of the resulting string - which will only be the case if your input file has fixed record length.

Instead of avoiding to use local $/ use it right - inside a BLOCK, so after leaving that block (at runtime) it gets its previous value:

{ local $/; # undef by default if localized # file slurp here } # after the block, original $/ is restored

Try e.g. perl -le "{ local $/ = '@'; print ord $/,': ',$/ } print ord $/,': ',$/"

Result:

64: @ 10:

Read up chomp. That line

push(@records, chomp($record));

doesn't do what you expect. with $/ set to undef your array @records will contain only empty (undef) elements.

See also my/local, space/time (was: Re: The difference between my and local).


In reply to Re: Avoid using local $/=undef? by shmem
in thread Avoid using local $/=undef? by irDanR

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.