pc88mxer has asked for the wisdom of the Perl Monks concerning the following question:

Is there a magic perl way to reference the null file handle, <>, so that

while (<$handle>) { ... }

is the same as

while (<>) { ... }?

I looked on CPAN for a Tie:: module, but I didn't find anything.

Replies are listed 'Best First'.
Re: Referencing the null file handle, <>
by moritz (Cardinal) on Jun 05, 2008 at 17:17 UTC
    use strict; use warnings; sub cat_all { my $fh = shift; print while <$fh>; } cat_all \*ARGV;
    work for me, so ARGV is the answer.

    BTW I found this by inspecting the output of perl -MData::Dumper -wle 'print Dumper [ keys %::]'. Looking at perlvar also helped.

      Quoting from perlvar:
      ARGV
      The special filehandle that iterates over command-line filenames in @ARGV. Usually written as the null filehandle in the angle operator <> . Note that currently ARGV only has its magical effect within the <> operator; elsewhere it is just a plain filehandle corresponding to the last file opened by <>. In particular, passing \*ARGV as a parameter to a function that expects a filehandle may not cause your function to automatically read the contents of all the files in @ARGV.
      So what you posted won't work. I don't know of any way reproduce the same function with a passed parameter, although I suspect a tied file handle would be the best way to do so.

        It works for me; that is, (on my particular systems with the particular versions of Perl I'm using,) passing \*ARGV to a (trivial) function that expects a filehandle certainly does cause it to read the contents of all the files in @ARGV, even if I have reassigned @ARGV since the last read from <>.

        So, I'm now intrigued by that "may not" there. What are the conditions where it doesn't work? Is it platform-based? version-based? phase-of-moon-based...?

Re: Referencing the null file handle, <>
by Joost (Canon) on Jun 05, 2008 at 18:27 UTC
Re: Referencing the null file handle, <>
by apl (Monsignor) on Jun 05, 2008 at 17:46 UTC
    Run your program redefining STDIN as the file you're interested in (perl Script.pl <input.txt).
Re: Referencing the null file handle, <>
by smokemachine (Hermit) on Jun 06, 2008 at 13:05 UTC
    perl -e 'print while <ARGV>'
    if you give a(some) file(s), it will read the file(s), elsif will read the stdin