perl - Getopt::Long 带有特殊字符选项(例如 -%)

标签 perl optional-parameters

在 perl 脚本中,我使用 Getopt::Long 在调用脚本时解析命令行选项。

现在,我想添加一个选项-%:

die unless GetOptions (
    'x=i' => \my $x,
    'y:i' => \my $y,
    'z'   => \my $z,
    '%'   => \my $percent
);

但是,这会导致选项规范错误:“%”。我当然可以使用 'pct' =>\my $percent 而不是 '%' =>\my $percent 但我觉得 的助记符值-% 更高。

那么,通过 Getopt::Long 是否可以实现我想要的效果?或者是否有另一个选项解析器模块可以完成我想要的事情?

最佳答案

我强烈建议不要使用 -% 作为选项...通常的做法是使用 62 个可用的单个字符或更详细的长选项中的任何一个。

-% 到底是什么意思?它或多或少是不是一种需要处理另一个参数选项的“单元”?

draw_rect .... --opacity 0.75 # for a range between 0 .. 1.000
draw_rect .... --opacity 75 % # for a range between 0 .. 100.0

calculate_new_prices --discount 3.50 USD # for $3,50 less ?
calculate_new_prices --discount 3.50 EUR # for €3,50 less ?
calculate_new_prices --discount 3.50     # for  3,50 discount in  .... ?
calculate_new_prices --discount 35.0 %   # for 35.00 % offers ?

Getopt::Long 知道如何处理具有多个值的选项,只需向其传递一个 ArrayRef:

GetOptions (
  ...
  'discount{1,2} => \@discount,
  ...
);

如果它确实是一个“开关”,那么它可能意味着某事物与其他事物“相对”,只需使用更详细的选项,即...“它是相对的”而不是“这是一个百分号“......

my_script ....  --relative

圣诞快乐

关于perl - Getopt::Long 带有特殊字符选项(例如 -%),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27645166/

相关文章:

c - 使用 perl XS 链接到 C 共享库

javascript - 构造 x = x || 是什么?你的意思是?

php - Yii 获取模型作为参数

perl - 等于 5 的四舍五入 float

scala - 使用可选参数映射 Scala 函数

c# - OptionalAttribute 参数的默认值?

javascript - 使用不同类型的一个参数重载 Typescript 方法(非原始)

perl - 我可以设置一个 perl 脚本吗?

linux - 运行 EasyApache 时出错

perl - 如何访问 If/else 范围之外的值