【问题标题】:How to pass a file using GetOpt如何使用 GetOpt 传递文件
【发布时间】:2012-07-11 17:11:13
【问题描述】:

我有一个程序,我需要将文件名(和位置)传递给程序。我怎样才能做到这一点?我已经阅读了 GetOpt 文档,所以请不要指向我那里。我的命令行如下:

perl myprogram.pl -input C:\inputfilelocation -output C:\outputfilelocation

我的 GetOptions 如下所示:

GetOptions('input=s' => \$input,'output=s' => \$output);

基本上我需要弄清楚如何在我拥有的 while 循环中访问该文件,该循环遍历文件中的行并将每个行放入 $_

while ($input) {

...不起作用。请注意,在我的文件正常工作之前:

open my $error_fh, '<', 'error_log';
while (<$error_fh>) { 

【问题讨论】:

    标签: perl command-line getopt


    【解决方案1】:

    这对我有用。您的 GetOptions 似乎是正确的。打开文件并从文件句柄中读取,不要忘记检查错误:

    use warnings;
    use strict;
    use Getopt::Long;
    
    my ($input, $output);
    GetOptions('input=s' => \$input,'output=s' => \$output) or die;
    
    open my $fh, '<', $input or die;
    
    while ( <$fh> ) { 
        ## Process file.
    }
    

    【讨论】:

    • 我的死在:open my $fh, '
    • @user1488984 为什么会死掉?在 die 消息中包含错误:...or die $!
    • @TLP:它在关闭文件句柄 $fh 上说“readline():while () {
    • 我忘了说 while 语句在子例程中,如果这很重要的话。
    • @user1488984 这意味着要么您从未打开过文件句柄,要么打开失败。如果您的 open 语句中有 or die,这意味着您的文件句柄超出范围,或者您拼错了变量名。没有看到你的代码很难猜到。
    【解决方案2】:

    您的代码似乎假定您被传递的是文件句柄,而不是文件名。您需要打开文件并为其分配文件句柄。

    # This doesn't work as $input contains a file name
    GetOptions('input=s' => \$input,'output=s' => \$output);
    
    # This doesn't work for two reasons:
    # 1/ $input is a file name, not a filehandle
    # 2/ You've omitted the file input operator
    while ($input) {
      ...
    }
    

    你想要更像这样的东西:

    # Get the file names
    GetOptions('input=s' => \$input,'output=s' => \$output);
    
    # Open filehandles
    open my $in_fh, '<', $input or die "Can't open $input: $!";
    open my $out_fh, '>', $output or die "Can't open $output: $!";
    
    # Read the input file using a) the input filehandle and b) the file input operator
    while (<$in_fh>) {
      ...
    }
    

    我也认为这里可能还有另一个问题。我不是 Windows 专家,但我认为您的文件名可能会被误解。尝试在命令行中反转斜杠:

    perl myprogram.pl -input C:/inputfilelocation -output C:/outputfilelocation
    

    或加倍反斜杠:

    perl myprogram.pl -input C:\\inputfilelocation -output C:\\outputfilelocation
    

    或者引用参数:

    perl myprogram.pl -input "C:\inputfilelocation" -output "C:\outputfilelocation"
    

    【讨论】:

      猜你喜欢
      • 2016-02-01
      • 2013-10-21
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多