|There's more than one way to do things|
read ARGV ==> read on unopened filehandleby ambrus (Abbot)
|on Sep 17, 2005 at 13:15 UTC||Need Help??|
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
dies with the following message whether it's got a file name as argument or not:
To correct this, a simple way is to use the eof function which does know about 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.