What is the slickest way to programatically read from stdin or an input file (if provided) in Perl?
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;
Here is how I made a script that could take either command line inputs or have a text file redirected.
if ($#ARGV < 1) {
@ARGV = ();
@ARGV = <>;
chomp(@ARGV);
}
This will reassign the contents of the file to @ARGV, from there you just process @ARGV as if someone was including command line options.
WARNING
If no file is redirected, the program will sit their idle because it is waiting for input from STDIN.
I have not figured out a way to detect if a file is being redirected in yet to eliminate the STDIN issue.