stdin - default file source for <> in perl -
i want read data <> operator.
it reads data stdin or files specified script's args
but, if no stdin presented, nor file specified, want read data default file path;
so, should
my $file = ''; if ($argc) { open $file, '<default.txt'; } while (<$file>) # if no args should <> { do_all; }
the <>
operator reads list of input file names @argv
. thus, 1 way set default input file name check if @argv
empty, , if so, push default file name onto it:
push @argv, "default.txt" unless @argv;
i'm not sure mean "no stdin presented", if mean want script read foo.txt
instead of default.txt
if invoked e.g.:
perl script.pl < foo.txt
or:
cat foo.txt | perl script.pl
then checking whether stdin
reading terminal or not, using -t
file test. if stdin
not tty, pipe or file, , should try read it:
push @argv, "default.txt" unless @argv or !-t stdin;
Comments
Post a Comment