首页 > 解决方案 > 如何在 Perl 中以命令行选项格式将列表作为输入

问题描述

我正在尝试使用输入的命令行选项从用户那里获取一个列表。perl 脚本如下所示。此处输入 3 必须是从 shell 提供的列表。我不知道我应该在列表中放什么,因此使用了一个字符串。

my %Inputs =(
  "Company_name=s"        =>\my $Input1,
  "Place=s"               =>\my $Input2,
  "Revenue=s"             =>\my @Input3,
  "No_of_Employee=i"      =>\my $Input4,
);

These Inputs are then used inside a subroutine

subroute ($Input1, $Input2, @Input3, $Input4);

输入的命令行格式是

./my.pl -Input1 user/file1 -Input2 user/file2 -Input3 ...

我不知道我应该如何以及以什么格式在命令行中输入列表。并且在将列表作为输入时,我应该将其指定为字符串还是列表。

标签: perl

解决方案


看起来您正在使用Getopt::Long。关于重复参数的文档提供了多种方法来做到这一点。

您编写代码的方式允许您多次重复相同的参数。

GetOptions( "foo=s" => \my @foo);
print Dumper \@foo;

# $ ./bar.pl --foo hello --foo world
# [ "foo", "bar" ]

或者,您可以使其在同一选项上采用多个值。

GetOptions( "foo={,}" => \my @foo);
print Dumper \@foo;

# $./bar.pl --foo hello world "how are you?"
# [ "foo", "bar", "how are you?" ]

{,}意味着它需要零个或多个输入,使其成为可选的。它类似于正则表达式量词。你也可以这样做:

  • {2}- 正好两个
  • {2,}- 两个或更多
  • {2,4}- 两个或四个之间

推荐阅读