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

Is there any possible way of equating file handles?

My program takes in any number of files including a '-' or none which would then read from STDIN. The problem is, i'm doing something like so:

foreach $file (@files) { if ((!open (FILE, "<file")) && ($file ne '-')) { #print error and die } else { while ($line = <FILE>) #OR if FILE is undefined then <STDIN> { #do something } } }
I'd like to be able to just make FILE equal STDIN before so i don't have to fiddle around with anything in the condition of the loop. (Unless it happens to be really nice and simple to do it in the condition).

Replies are listed 'Best First'.
Re: Equate File Handles?
by ikegami (Patriarch) on May 07, 2009 at 02:58 UTC
    Don't you simply want open(FILE, $file)?
    $ echo foo > foo.txt $ perl -e'open FILE, $ARGV[0] or die $!; print <FILE>' foo.txt foo $ echo foo | perl -e'open FILE, $ARGV[0] or die $!; print <FILE>' - foo $ perl -e'open FILE, $ARGV[0] or die $!; print <FILE>' 'echo foo |' foo $ perl -e'open FILE, $ARGV[0] or die $!; print <FILE>' 'cat foo.txt |' foo

    If you want STDIN to be the default, prepend @ARGV = '-' if !@ARGV;.

    $ echo foo | perl -e'@ARGV = "-" if !@ARGV; open FILE, $ARGV[0] or die + $!; print <FILE>' foo

    Perl does all of this for you when you use <ARGV> or its shorter form <>.

    $ perl -e'print <>' foo.txt foo $ echo foo | perl -e'print <>' - foo $ echo foo | perl -e'print <>' foo $ perl -e'print <>' 'echo foo |' foo $ perl -e'print <>' 'cat foo.txt |' foo

    Is there any possible way of equating file handles?

    Equating? Sounds like comparing, but I think you mean assigning. If so, yes. FILE is short for *FILE. If you use the latter form, you'll have no problem.

    *FILE = *STDIN; $fh = *STDIN; $fh = \*STDIN; # Ref often allowed and even preferred.
Re: Equate File Handles?
by Anonymous Monk on May 07, 2009 at 02:39 UTC
    Okay so it's working. But i'm not sure why.

    I've done absolutely nothing to the code except add '-' to @files if wanted. Does <FILE> automatically go to STDIN if undefined?