This meditation is about a peculiarity of perl we've discussed in the CB ages ago. I'm sorry but I can't remember who answered my question that time. Anyway, I think this is worthwile to write down, so that if anyone else runs into the same problem, they would find it with super-search.

You have to take care if you try to read the special ARGV filehandle, as some functions – including read – don't know about it being special.

For example, the following code

'read ARGV, $b, 1<<12 or die "cannot read ARGV: $!";
dies with the following message whether it's got a file name as argument or not:
read() on unopened filehandle ARGV at -e line 1. cannot read ARGV: Bad file descriptor at -e line 1.

To correct this, a simple way is to use the eof function which does know about ARGV:

() = eof(); read ARGV, $b, 1<<12 or die "cannot read ARGV: $!";
This code does what you mean, i.e. it reads at most 4K bytes from the standard input or the file given as command line argument.

(The () = is there only to supress the warning about eof in void context.)

(Update: spelling corrected, as noted by cchampion)

Update: the consensus is currently that using read on ARGV is bad practice. Nevertheless, even that can be valuable information for someone who is struggling with the same bug, so this meditation still has a point. Thanks for all explanations.


In reply to read ARGV ==> read on unopened filehandle by ambrus

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.