Search code examples
perlcoding-styleperl-critic

Why should I use <ARGV> or <> instead of <STDIN> in Perl?


Quoting from Perl::Critic::Policy::InputOutput::ProhibitExplicitStdin

Perl has a useful magic filehandle called *ARGV that checks the command line and if there are any arguments, opens and reads those as files. If there are no arguments, *ARGV behaves like *STDIN instead. This behavior is almost always what you want if you want to create a program that reads from STDIN. This is often written in one of the following two equivalent forms:

while (<ARGV>) {
  # ... do something with each input line ...
}
# or, equivalently:
while (<>) {
  # ... do something with each input line ...
}
  • Is it "just a convention" or are there some solid reasons not to use <STDIN> ?

I feel <STDIN> makes my code's intentions more clear than using <> or <ARGV>.

The flow of my code is like this

my @inp = <STDIN>;
my $len = $inp[0];

...

for(my $i = 0; $i < ($len + 0); $i++) {
    my @temp = split (' ', $inp[$i]);
    ...
}

Solution

  • It's because using <ARGV> will enable users to either specify files to read from as arguments, or pipe stuff into stdin while specifying no arguments. If you use <STDIN>, only piping will work.

    Of course it's up to you to decide if you think people would like to be able to specify files as command line arguments, but it's something a lot of programs support so it might be worth thinking about.