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

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

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

    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 }