0

我知道我在这里做了一些愚蠢的事情,但我很累而且我显然只是没有看到它。我有以下脚本:

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

my @names = (
    "John Q. Public",
    "James K Polk"
);

foreach (@names)
{
    print "Before: $_\n";
    s/\b[A-Z]\.?\b//;
    print "After:  $_\n";
}

当我运行这个脚本时,我得到以下输出:

Before: John Q. Public
After:  John . Public      <== Why is the period still here?
Before: James K Polk
After:  James  Polk

请注意,在John Q. Public示例中,保留了句点。可选的匹配参数 ( ?) 不是贪婪的吗?根据perlre 文档

? 匹配 1 或 0 次

句号不应该和中间的首字母一起消失吗?我在这里想念什么?

4

2 回答 2

4

问题是

". " =~ /\.\b/ or print "There is no word boundary between a dot and a space.\n"
于 2012-11-30T19:12:16.970 回答
1

我想我会选择在空格上拆分名称并仅选择第一个和最后一个字段。

像这样:

use strict;
use warnings;

my @names = ("John Q. Public", "James K Polk");

foreach (@names) {
  print "Before: $_\n";
  $_ = join ' ', (split)[0, -1];
  print "After:  $_\n";
}

输出

Before: John Q. Public
After:  John Public
Before: James K Polk
After:  James Polk
于 2012-12-04T21:33:02.057 回答