Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default file source for <> in perl

Tags:

stdin

perl

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;
}
like image 996
xoid Avatar asked Mar 18 '23 17:03

xoid


2 Answers

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;
like image 70
Ilmari Karonen Avatar answered Mar 25 '23 06:03

Ilmari Karonen


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;
like image 38
mpapec Avatar answered Mar 25 '23 07:03

mpapec