I want to read data by <> operator.
It reads data from stdin or from files specified as script's args
But, if no STDIN presented, nor file specified, I want to read data from default file path;
So, it should be like
my $file = '';
if ($ARGC) { open $file, '<default.txt'; }
while (<$file>) # if no ARGs it should be <>
{
do_all;
}
The <>
operator reads the list of input file names from @ARGV
. Thus, one way to set up a default input file name is just to check if @ARGV
is empty, and if so, push your default file name onto it:
push @ARGV, "default.txt" unless @ARGV;
I'm not sure what you mean by "no STDIN presented", but if you mean that you want your script to read from foo.txt
instead of default.txt
if invoked as e.g.:
perl script.pl < foo.txt
or:
cat foo.txt | perl script.pl
then you do this by checking whether STDIN
is reading from a terminal or not, using the -t
file test. If STDIN
is not a tty, it is most likely a pipe or a file, and thus you should try to read from it:
push @ARGV, "default.txt" unless @ARGV or !-t STDIN;
But, if no STDIN presented, nor file specified, I want to read data from default file path
I guess that by "no STDIN" you are referring to no piping on perl STDIN
push @ARGV, "default.txt" if !@ARGV and -t STDIN;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With