在Perl模式匹配中打印匹配的字符串
我希望它打印“type=build”,但$1什么也得不到,它打印“type=”,我做错了什么?您没有在正则表达式中捕获任何内容。括号必须在模式内,如下所示在Perl模式匹配中打印匹配的字符串,perl,Perl,我希望它打印“type=build”,但$1什么也得不到,它打印“type=”,我做错了什么?您没有在正则表达式中捕获任何内容。括号必须在模式内,如下所示 use strict; my $type = "build"; if ($type =~ (/build|test/)) { print "type=$1"; } 你没有在正则表达式中捕获任何东西。括号必须在模式内,如下所示 use strict; my $type = "build"; if ($type =~ (/build|
use strict;
my $type = "build";
if ($type =~ (/build|test/))
{
print "type=$1";
}
你没有在正则表达式中捕获任何东西。括号必须在模式内,如下所示
use strict;
my $type = "build";
if ($type =~ (/build|test/))
{
print "type=$1";
}
看起来你没有用括号捕捉任何东西
if ( $type =~ /(build|test)/ ) {
print "type=$1";
}
输出
perl -MO=Deparse -e'
use strict;
my $type = "build";
if ($type =~ (/build|test/))
{
print "type=$1";
}
'
但是
/(build | test)/
应该完全是另一回事。看起来你没有用括号捕捉任何东西
if ( $type =~ /(build|test)/ ) {
print "type=$1";
}
输出
perl -MO=Deparse -e'
use strict;
my $type = "build";
if ($type =~ (/build|test/))
{
print "type=$1";
}
'
但是
/(build | test)/
应该完全是另一回事。这就是为什么这里的人建议使用警告和严格。
如果在代码中添加使用警告
,您将得到警告:
use strict;
my $type = 'build';
if ($type =~ /build|test/) {
print "type=$1";
}
代码是:
Use of uninitialized value $1 in concatenation (.) or string at type.pl line 7
这就是为什么这里的人建议使用使用警告
和使用严格的
。
如果在代码中添加使用警告
,您将得到警告:
use strict;
my $type = 'build';
if ($type =~ /build|test/) {
print "type=$1";
}
代码是:
Use of uninitialized value $1 in concatenation (.) or string at type.pl line 7
我认为这篇文章可以帮助你得到答案:提示:使用警告
我认为这篇文章可以帮助你得到答案:提示:使用警告
是的,它有效,谢谢。@Krish:如果这解决了你的问题,接受这个作为答案并关闭这个。是的,它有效,谢谢。@Krish:如果这解决了你的问题,接受这个答案,结束这个。我不明白你在说什么。你只是在证明括号没有区别吗?这似乎不是问题的解决方案。是的,答案的结尾是建议解决方案。好的。但是“/(build | test)/
应该完全是另一回事”看起来不像是一个提议的解决方案,甚至不是一个建议@Cyxon27,感谢您展示Deparse功能,但当我尝试检查时,它会抛出下面的错误,我得到了问题的答案,但我想知道如何使用DeparseC:\>perl-MO=Deparse-e'use strict;我的$type=“build”;如果($type=~(/build | test/){print“type=$1”;}'
搜索模式未在-e行1终止。测试:额外的参数“'@Krish在win下,你必须使用perl-e”。“
,和qq()
,而不是”
。我不明白你在这里说什么。你只是在证明括号没有区别吗?这似乎不是问题的解决方案。是的,答案的结尾是建议解决方案。好的。但是“/(build | test)/
应该完全是另一回事”看起来不像是一个提议的解决方案,甚至不是一个建议@Cyxon27,感谢您展示Deparse功能,但当我尝试检查时,它会抛出下面的错误,我得到了问题的答案,但我想知道如何使用DeparseC:\>perl-MO=Deparse-e'use strict;我的$type=“build”;如果($type=~(/build | test/){print“type=$1”;}'
搜索模式未在-e行1终止。测试:win下的额外参数“'@Krish”必须使用perl-e.“
,以及qq()
,而不是”
。