【问题标题】:Perl - en / em dash in command line argumentsPerl - 命令行参数中的 en / em 破折号
【发布时间】:2016-06-30 08:17:09
【问题描述】:

我的 perl 脚本在解析命令行参数时遇到问题。主要是,我希望 perl 解析以 (em/en)-dash 和 hypen 开头的参数。 请考虑以下命令执行:

my_spript.pl -firstParam someValue –secondParam someValue2

如您所见,firstParam 以 hypen 为前缀,perl 解析它没有问题,但 secondParam 以 en-dash 为前缀,不幸的是 Perl 无法将其识别为参数。 我正在使用 GetOptions() 来解析参数:

GetOptions(
    "firstParam" => \$firstParam,
    "secondParam" => \$secondParam
)

【问题讨论】:

  • 你使用什么模块? Getopt::Long?
  • @choroba,是的。我确实使用 Getopt::Long
  • 恕我直言,这是一个疯狂的要求。

标签: perl parsing arguments args hyphen


【解决方案1】:

如果您使用的是Getopt::Long,则可以在将参数提供给GetOptions之前对其进行预处理:

#! /usr/bin/perl
use warnings;
use strict;

use Getopt::Long;

s/^\xe2\x80\x93/-/ for @ARGV;

GetOptions('firstParam:s'  => \ my $first_param,
           'secondParam:s' => \ my $second_param);
print "$first_param, $second_param\n";

不过,首先解码参数可能更简洁:

use Encode;

$_ = decode('UTF-8', $_), s/^\N{U+2013}/-/ for @ARGV;

要在不同的语言环境设置下工作,请使用Encode::Locale

#! /usr/bin/perl
use warnings;
use strict;

use Encode::Locale;
use Encode;
use Getopt::Long;

$_ = decode(locale => $_), s/^\N{U+2013}/-/ for @ARGV;

GetOptions('firstParam:s'  => \ my $first_param,
           'secondParam:s' => \ my $second_param);
print "$first_param, $second_param\n";

【讨论】:

  • 在 OS-X 上很好,但在 Windows 上似乎不起作用。 (perl 版本:5.14.2)。您知道可能出了什么问题吗?
  • 在 Windows 上,终端编码可能不是 UTF-8。指定正确的编码。
猜你喜欢
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
相关资源
最近更新 更多