Making cosmetic changes in the presence of magic is rarely advisable. So I suppose I shouldn't have been surprised when changing <ARGV> to <> broke a working script.

The context here is the dumping of all input to a temporary file:

my ($fh, $nam) = File::Temp::tempfile; print $fh <ARGV>;

This works. But changing the second line to

print $fh <>;

causes it to fail with the message "syntax error ... near <>".

This puzzled me for a long time. Surely <> and <ARGV> are synonyms? Why would one work and the other fail?

For about five minutes after this dawned on me, I wished that Perl had just a little more magic in it, so that my change wouldn't have broken anything. But then I realised that adding more magic would just make the cases where it doesn't DWIM even more unexpected and confusing. I note in passing that Perl 6 will use a less ambiguous syntax that won't break this way. Which I like, even though it looks a bit ugly to me at the moment. I want the experience of programming to be magical, not the syntax.

Replies are listed 'Best First'.
Re: <> and <ARGV> are the same thing, except when they aren't
by ikegami (Patriarch) on Sep 17, 2009 at 21:12 UTC

    Indeed, determining if what follows print is a file handle or not is very finicky. Since the parser always favours an expression to print over a handle, you can force unambiguity using curlies:

    print { $fh } ...;

    Note that contrary to what you said, indirect method calls are not affected, just the print operator.

    $ echo foo | perl -MCGI -e'new CGI <>;' $

    Update: Last bit is wrong.

    $ perl -c -e'method $foo <>;' syntax error at -e line 1, near "<>" -e had compilation errors. $ perl -c -e'method $foo <ARGV>;' -e syntax OK