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

Dear Monks,

For practice, I am trying to write a perl program that will read from files listed on the command line--without using the diamond operator (<>). For example, if the program is invoked like this:

perl myprog.pl fred.txt - barney.txt

I want to read from the file fred.txt, the file '-' which represents STDIN, and lastly barney.txt. When I try to do the equivalent of this:

my $fname = '-'; ... ... my $INFILE; if(!open ($INFILE, "<", $fname)) { print "current file name: $fname\n"; die ".....$!"; }

I am unable to open the file:

current file name: - .....No such file or directory ...

1) Why do I get that error? I guess I confused "reopening a file handle will cause perl to automatically close the old one", with opening a new file handle connected to a file where the file is already connected to another open file handle. But then why doesn't the error message say, "File already open" or something like that?

2) What is the best way to deal with a '-' on the command line? Check each element of @ARGV for '-'? This works ok for me:

use strict; use warnings; if (!@ARGV) { push @ARGV, '-'; } foreach my $arg (@ARGV) { print "$arg\n"; } while(my $fname = pop @ARGV) { my $INFILE; if ($fname eq '-') { $INFILE = *STDIN; }else{ if(!open ($INFILE, "<", $fname)) { say "current file name: $fname"; die ".....$!"; } } my @lines = <$INFILE>; foreach (reverse @lines) { print; } close $INFILE; } --output:--- data1.txt - data2.txt D #start output from data2.txt C B A #end output from data2.txt x #start STDIN input y z #end STDIN input zD #This started off as a blank line where I hit control-D for eof. y x line 4 #start output from data1.txt line 3 line 2 line 1 #end output from data1.txt
Thanks for any advice.

Replies are listed 'Best First'.
Re: reading from filename '-'
by zwon (Abbot) on Nov 07, 2009 at 10:28 UTC

    You're getting error because you're trying to open file named '-', not stdin. @ARGV works because <> operator uses two arguments open. Compare these:

    open my $fd, "<", "-"; # will try to open file "-" open my $fd, "-"; # will open STDIN

    Update: concerning second question, the best practice is to use three arguments form of open, so you solution is ok.

      Thanks. The two arg form of open() works great!
Re: reading from filename '-'
by jwkrahn (Abbot) on Nov 07, 2009 at 10:30 UTC

    What you want to do will work with the one or two argument versions of open but not with the three argument version.