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

时光毁灭记忆、已成空白 提交于 2019-12-05 10:32:04

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.

brian d foy

You use the one that does what you want to do. See perlvar for an explanation of the ARGV filehandle. ARGV also reads from filenames you specify on the command line. Maybe you want that feature, maybe you don't.

And, you don't have to do what Perl::Critic says. Many of those policies are the opinions of a small group of people. If you only want to read from STDIN explicitly, that's what you need to do. The people writing the Critic policies aren't there to state what you need to do. Asking any question like this is mostly pointless without the context of its application. General rules are merely general, and break down when talking about specific cases.

I'm not sure why you think your intent is clearer with STDIN because you didn't tell us your intent. Code almost never speaks for itself because we tend to code the solution instead of stating the problem. The solution might not be the right one.

In your case, I think this code is more clear because it's written in Perl instead of the C dialect you're using :)

 chomp( my $length = <STDIN> );

 my $count = 0;
 while ( <STDIN> ) {
     last if $count++ > $lines_to_read; 

     my @temp = split ' ';
     ...;
     }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!