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.

In reply to reading from filename '-' by 7stud

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.