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
2010-06-29 07:25:44
+9
A:
while (<>) {
print;
}
will read either from a file specified on the command line or from stdin if no file is given
ennuikiller
2010-06-29 07:28:56
+1 +nitpick: "will read from one or more files consecutively specified on the command line"
msw
2010-06-29 07:57:31
...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
2010-06-29 13:54:05
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
2010-06-29 07:44:54
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
2010-06-29 08:27:16