为什么要使用< ARGV>或<>而不是< STDIN>在Perl? [英] Why should I use <ARGV> or <> instead of <STDIN> in Perl?

查看:158
本文介绍了为什么要使用< ARGV>或<>而不是< STDIN>在Perl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用自 Perl ::批评: :Policy :: InputOutput :: ProhibitExplicitStdin


Perl有一个有用的魔术文件句柄叫做ARGV它检查命令行,如果有任何参数,打开并读取它们作为文件。如果没有参数,* ARGV的行为类似于* STDIN。如果你想创建一个从STDIN读取的程序,这种行为几乎总是你想要的。这通常以以下两种等效形式之一书写:

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 ...
}





  • 它是只是一个公约还是有一些固定的理由不使用< STDIN>

    • Is it "just a convention" or are there some solid reasons not to use <STDIN> ?
    • 我觉得< STDIN> 使我的代码的意图比使用< code>或< ARGV>

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

      我的代码流程如下

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


      推荐答案

      这是因为使用< ARGV> 将允许用户指定要读取的文件作为参数,或管道材料到stdin同时指定没有参数。如果你使用< STDIN> ,只有管道可以工作。

      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.

      这篇关于为什么要使用&lt; ARGV&gt;或&lt;&gt;而不是&lt; STDIN&gt;在Perl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆