tags:

views:

104

answers:

3

What is the slickest way to programatically read from stdin or an input file (if provided) in Perl?

+4  A: 

You need to use <> operator:

while (<>) {
    print $_; # or simply "print;"
}

Which can be compacted to:

print while (<>);

Arbitrary file:

open F, "<file.txt" or die $!;
while (<F>) {
    print $_;
}
close F;
el.pescado
+9  A: 
while (<>) {
print;
}

will read either from a file specified on the command line or from stdin if no file is given

ennuikiller
+1 +nitpick: "will read from one or more files consecutively specified on the command line"
msw
...and all you need to do is write `@ARGV = "/path/to/some/file.ext";` and it reads the file--so you can even program a default file on certain conditions.
Axeman
A: 
if(my $file = shift) { # if file is specified, read from that
  open(my $fh, '<', $file) or die($!);
  while(my $line = <$fh>) {
    print $line;
  }
}
else { # otherwise, read from STDIN
  print while(<>);
}
trapd00r
The plain `<>` operator will automatically find and read from any file(s) given on the command line. There's no need for the `if`.
Dave Sherohman