在比较中使用正则表达式的结果

Using results of regular expression in a comparison

我正在尝试在比较操作中使用模式匹配的结果。似乎无法正常工作。

此处的 if 语句 returns 为假:

if (('6kjkjd' =~ /(\d)/) > 5) {
  print "Why isn't this printing? 6 is greater than 5.";
}

还有这里:

my $start;
if ((($start) = '6kjkj' =~ /(\d)/) > 5) {
  print "Why isn't this printing? 6 is greater than 5.";
}

我试过从比较操作的左侧删除括号,但结果总是得到一个真值:

my $start;
if (($start) = '6kjkj' =~ /(\d)/ > 7) {
  print "This gets printed even though 6 is not greater than 7.";
}

我意识到我可以像这样把它分成两行:

my ($start) = '6kjkj' =~ /(\d)/;
if ($start > 5) {
  print "This works as expected.";
}

不过,我还是很想知道为什么前三个代码示例无法像您预期的那样工作。

列表与标量上下文:

if (('6kjkjd' =~ /(\d)/)[0] > 5) {
    print "Why isn't this printing? 6 is greater than 5.";
}

基本上,在 if 条件的范围内,您处于标量环境中。

当你写:

my $start;
if ((($start) = '6kjkj' =~ /(\d)/) > 5)

$start 的赋值发生了,但是列表 ($start) 只有一个元素。

如果你坚持要写一个复杂的表达式而不是把事情分解成碎片,你可以利用逗号运算符:

if ((($start) = '6kjkj' =~ /(\d)/), $start > 5) {
  print "Why isn't this printing? 6 is greater than 5.";
}

正如 Sam Choukri 在评论中指出的那样,

if (('6kjkj' =~ /(\d)/) and ( > 5)) {

比我首先想到的两种选择更安全、更简单。

那是因为运算符 =~ 在标量上下文中 returns 操作成功。

list-context(通过添加 [0]):

if ((('6kjkjd' =~ /(\d)/)[0]) > 5)
{
  print "Why isn't this printing? 6 is greater than 5.";
}