in reply to How to accept ARG from PIPE or STDIN?

while (<>) { # do something with $_ }
This will, assuming $\ has not been messed with, loop for each line of input via:
# cat myfile.txt | dosomething.pl
and
# dosomething.pl < myfile.txt
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.

Replies are listed 'Best First'.
Re^2: How to accept ARG from PIPE or STDIN?
by ikegami (Patriarch) on Mar 17, 2005 at 03:02 UTC

    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
      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 }