perl - 我可以替换并返回不带 $+ 的括号的匹配部分吗?

标签 perl substitution

下面的代码基本上实现了我想要实现的目标:它替换变量的一部分并将替换值的一部分分配给$foo:

my $value = "The foo is 42, but the bar is 12!";

my $foo = $+ if $value =~ s/foo is (\d+)//;

print "foo: $foo\n" if $foo;
print $value, "\n";

我的问题是这是否是“正确的方法”。特别是,我对 $foo = $+ if ... s/.../.../ 构造不太满意,想知道是否有一种(我觉得)更优雅的方式来做到这一点。

最佳答案

很难知道您要表达的是什么内容,但这里有一些为什么要这样写的原因。

你不应该永远写这样的东西

my $foo = $+ if $value =~ s/foo is (\d+)//

因为结果是官方未定义的。 perldoc perlsyn有话要说

NOTE: The behaviour of a my, state, or our modified with a statement modifier conditional or loop construct (for example, my $x if ...) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it.

另外,最好使用捕获变量$1,因为它更明确,而且很多人可能不知道$+ 的作用。而且测试替换是否成功比定义 $foo 更具描述性。

我会写这样的东西

my $value = "The foo is 42, but the bar is 12!";

if ( $value =~ s/foo is (\d+)// ) {
  my $foo = $1;
  print "foo: $foo\n";
}

print $value, "\n";

关于perl - 我可以替换并返回不带 $+ 的括号的匹配部分吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28607187/

相关文章:

python - 有没有办法撤消递归正则表达式操作?

BASH 脚本无需替换即可将变量传递到新脚本中

apache - httpd 替代品无法使用(环境)变量(依赖于请求)

perl - “Search Queries” 来自 Google WMT 的数据

regex - Perl regexp - 检索要列出的所有匹配项并将其从文本中删除

当部分条目包含字符时,Perl 对数组进行数字排序

perl - 让 Perl 将完整的 "key path"打印到值中(Data::Dumper 不会)

perl - 如何使用 PDF 基元绘制实心和非实心圆?

bash,用另一个变量替换部分变量

c++ - 替换在模板参数推导中如何工作?