in reply to Re: How to accept ARG from PIPE or STDIN?
in thread How to accept ARG from PIPE or STDIN?

If you wanted to do:

dosomething.pl myfile.txt

You need to get the filename from the first element in @ARGV, the arguments array. You may also want to check out Multiple STDIN sources.

No. <> treats as a list of file names, and opens each of them in turn. <> only reads from STDIN if @ARGV is empty. In other words,

while (<>) { # do something with $_ }

works for all of the following:

cat myfile.txt | dosomething.pl dosomething.pl < myfile.txt dosomething.pl myfile.txt

Replies are listed 'Best First'.
Re^3: How to accept ARG from PIPE or STDIN?
by monkfan (Curate) on Mar 17, 2005 at 03:16 UTC
    But how about, if I want to use "die" command in this standard context?
    open INFILE, "<$file" or die "$0: Can't open file $file: $!"; while (<INFILE>){ # do something with $_ }
    Does it still work?
    Regards,
    Edward

      Then you can do something like:

      my $file = $ARGV[0]; if (defined $file) { open(IN, "< $file") or die("Unable to open supplied argument: $!\n"); } else { *IN = *STDIN; } while (<IN>) { print($_); # do stuff }

      or with some magic:

      my $file = @ARGV ? $ARGV[0] : '-'; open(IN, "< $file") or die("Unable to open input file: $!\n"); while (<IN>) { print($_); # do stuff }

      or the OO way:

      use FileHandle; my $file = $ARGV[0]; my $fh_in; if (defined($file)) { $fh_in = FileHandle->new($file, 'r') or die("Unable to open supplied argument: $!\n"); } else { $fh_in = *STDIN{IO}; } while (<$fh_in>) { print($_); # do stuff }