【问题标题】:Giving both input & output file at command line在命令行同时提供输入和输出文件
【发布时间】:2014-07-24 11:22:50
【问题描述】:

我在 perl 脚本中有这一行,它将输出打印到 STDOUT/控制台

printf "Line no. $i"

我应该在程序中包含哪些代码来将此输出定向到用户在命令行本身给出的输出文件(如下所述)

现在,以下部分要求用户输入文件:

print "enter file name";
chomp(my $file=<STDIN>);
open(DATA,$file) or die "error reading";

但我不想向用户询问输入/输出文件中的任何一个。 我想要的是一种用户可以在运行程序时从命令行输入和输出文件的方式。

perl input_file output_file program.pl

我应该为此添加什么代码。

【问题讨论】:

    标签: perl file-io stdout


    【解决方案1】:

    您可以使用shift 来读取脚本的命令行参数。 shift 读取并删除数组的第一个元素。如果没有指定数组(并且不在子例程中),它将隐式从@ARGV 读取,其中包含传递给脚本的参数列表。例如:

    use strict;
    use warnings;
    use autodie;
    
    # check that two arguments have been passed
    die "usage: $0 input output\n" unless @ARGV == 2;
    
    my $infile = shift;
    my $outfile = shift;
    
    # good idea to sanitise the arguments here
    
    open my $in, "<", $infile;
    open my $out, ">", $outfile;
    
    while (<$in>) {
        print $out $_;
    }
    
    close $in;
    close $out;
    

    你可以像perl script.pl input_file output_file 这样调用这个脚本,它会将input_file 的内容复制到output_file

    【讨论】:

    • 嗨,汤姆,我这样做了(出于某些原因,我需要以 格式读取输入): - 打开我的 $in, "", $outfile;然后写输出我这样做 ====> print $out "%-4s: %20s, %-8s %6s\n", $_->[0], qq($_->[0] $_->[3]), $_->[2], $group{$_->[2]};
    • 所以你想从命令行指定的文件以及__DATA__中读取?请编辑您的问题以添加更多详细信息。
    • @Sunita 我看到您在最近的问题中使用了我的答案。不要忘记为您认为有用的答案投票,并接受最能回答您问题的答案。
    【解决方案2】:

    这里最简单的方法是忽略程序中的输入和输出文件。只需从 STDIN 读取并写入 STDOUT。让用户在调用您的程序时重定向这些文件句柄。

    您的程序如下所示:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    while (<STDIN>) {
      # do something useful to the data in $_
      print;
    }
    

    你这样称呼它:

    $ ./your_program.pl inputfile.txt > outputfile.txt
    

    这被称为“Unix 过滤器模型”,它是编写读取输入和产生输出的程序的最灵活方式。

    【讨论】:

      【解决方案3】:

      你可以使用@ARGV变量,

      use strict ; 
      use warnings ;
      
      if ( @ARGV != 2 ) 
      {
              print "Usage : <program.pl> <input> <output>\n" ;
              exit ;
      }
      open my $Input,$ARGV[0] or die  "error:$!\n" ;
      open my $Output,">>" .$ARGV[1] or die "error:$!\n";                         
      print $Output $_  while (<$Input> )  ;
      close ($Input) ;
      close ($Output) ;
      

      注意: 你应该运行perl program.pl input_file output_file这种格式的程序。

      【讨论】:

      • 是的,但您应该首先真正清理该输入。否则,即使是无意的,也会发生坏事。此外,您应该避免使用裸字文件描述符(可能会产生其他不良副作用)
      • @vol7ron,你能告诉我有什么副作用吗?
      • 删除文件、使磁盘崩溃、耗尽所有内存、读取应该是安全/受限制的数据等。外部输入是进入系统的最简单方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 2014-06-13
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2014-05-15
      • 1970-01-01
      相关资源
      最近更新 更多