Perl,如何将 argv 读取为散列?

Perl, how to read argv as hash?

所以,我已经阅读了一些关于如何使用 Getopt::Long 和类似库来处理 argv 选项的指南,但仍然不知道如何正确使用它,因为完全不清楚 (至于我)文档和指南。

我有一个脚本。它有下一个参数: -qp, -pr, -rp, -vr,其中大部分是文件名。

目前我有这个用法Getopt::Long,我觉得不合适,因为我每次都需要检查选项后面的内容:

for(my $i = 0; $i < @ARGV; $i+=2){
    if ($ARGV[$i] eq "-qp"){
        unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
            $query_params = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-pr"){
        unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-rp"){
            $params = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-vr"){
        unless ($ARGV[$i+1] eq "-vr" or $ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-rp"){
            $variables = $ARGV[$i+1];
        }
    }
    elsif ($ARGV[$i] eq "-rp"){
        unless ($ARGV[$i+1] eq "-qp" or $ARGV[$i+1] eq "-pr" or $ARGV[$i+1] eq "-vr"){
            $replace = $ARGV[$i+1];
        }
    }
} 

也许我不需要为 Unix 使用精确的 Getopt 库,我只需要将一些 args 传递给脚本。有什么办法可以让它更简单更正确吗?

Getopt::Long.

文档中的一个简单示例

您现在可以使用 script --qp=file1 --pr=file2 --rp=file2

调用此脚本

Getopt:Long 为您所做的是将命令行上给出的值整理到您告诉它放置它们的位置,以及一些基本验证(这里的 =s 意味着您期待一个字符串)。

例如,如果您想检查给定的文件是否存在,您需要手动执行此操作。

use strict;
use warnings;

use Getopt::Long;

my ($qp,$pr,$rp);
my $verbose;

GetOptions (
    "qp=s" => $qp,
    "pr=s" => $pr,
    "rp=s" => $rp,
    "verbose" => $verbose,
) or die "Error in command line arguments";

print "Being verbose.\n" if $verbose;

# Quick check all are there if they're all required (?)
die "qp,pr and rp are required!" if grep{ !$_ }($qp,$pr,$rp);

for my $fn ( $qp,$pr,$rp ){
    die "Cannot find file '$fn'" unless -f $fn;
}

print "you've given: qp $qp, pr $pr, rp $rp.\n";

与您的说法相反,您没有使用 Getopt::Long。但是你应该!

use strict;
use warnings qw( all );
use feature qw( say );

use File::Basename qw( basename );
use Getopt::Long   qw( );

my %opts; 

sub parse_args {
   %opts = ();
   Getopt::Long::Configure(qw( posix_default ));
   GetOptions(
      'help|h|?' => \&help,
      'qp:s' => $opts{qp},
      'pr:s' => $opts{pr},
      'rp:s' => $opts{rp},
      'vr:s' => $opts{vr},
   )
      or usage();
}

parse_args();

使用 :s 而不是 =s 使选项的参数成为评论中要求的可选参数。

完成上述任务的辅助子样本:

sub help {
   my $prog = basename([=11=]);
   say "usage: $prog [options]";
   say "       $prog --help";
   say "";
   say "Options:";
   say "   --qp path   ...explanation...";
   say "   --qp        ...explanation...";
   say "   --pr path   ...explanation...";
   say "   --pr        ...explanation...";
   say "   --rp path   ...explanation...";
   say "   --rp        ...explanation...";
   say "   --vr path   ...explanation...";
   say "   --vr        ...explanation...";
   exit(0);
}

sub usage {
   my $prog = basename([=11=]);
   warn(@_) if @_;
   warn("Try `$prog --help' for more information\n");
   exit(1);
}