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:
Thanks for any advice.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
In reply to reading from filename '-' by 7stud
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |