http://www.perlmonks.org?node_id=492858

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.