下面的代码基本上实现了我想要实现的目标:它替换变量的一部分并将替换值的一部分分配给$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
, orour
modified with a statement modifier conditional or loop construct (for example,my $x if ...
) is undefined. The value of themy
variable may beundef
, 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/