我试图在比较操作中使用模式匹配的结果。 似乎无法让它发挥作用。
if语句在这里返回false:
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."; }我已经尝试从比较操作的左侧删除parens,但这总是会产生一个真正的值:
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."; }尽管如此,我很想知道为什么前三个代码示例不能像您预期的那样工作。
I'm trying to use the result of pattern match in a comparison operation. Can't seem to get it to work.
The if statement returns false here:
if (('6kjkjd' =~ /(\d)/) > 5) { print "Why isn't this printing? 6 is greater than 5."; }As well as here:
my $start; if ((($start) = '6kjkj' =~ /(\d)/) > 5) { print "Why isn't this printing? 6 is greater than 5."; }I've tried removing the parens from the left side of comparison operation but that always results in a true value:
my $start; if (($start) = '6kjkj' =~ /(\d)/ > 7) { print "This gets printed even though 6 is not greater than 7."; }I realize I could break this into two lines like so:
my ($start) = '6kjkj' =~ /(\d)/; if ($start > 5) { print "This works as expected."; }Still, I'm curious to know why the first three code examples don't work as you might expect.
最满意答案
列表与标量上下文:
if (('6kjkjd' =~ /(\d)/)[0] > 5) { print "Why isn't this printing? 6 is greater than 5."; }基本上,在if -condition的范围内,您处于标量上下文中。
当你写:
my $start; if ((($start) = '6kjkj' =~ /(\d)/) > 5)$start的赋值发生了,但是list ($start)只有一个元素。
如果你坚持写一个复杂的表达式而不是把事情分成几部分,你可以利用逗号运算符:
if ((($start) = '6kjkj' =~ /(\d)/), $start > 5) { print "Why isn't this printing? 6 is greater than 5."; }正如Sam Choukri在评论中指出的那样,
if (('6kjkj' =~ /(\d)/) and ($1 > 5)) {比我最初想到的两种替代方案更安全,更简单。
List versus scalar context:
if (('6kjkjd' =~ /(\d)/)[0] > 5) { print "Why isn't this printing? 6 is greater than 5."; }Basically, within the confines of an if-condition, you are in scalar context.
When you write:
my $start; if ((($start) = '6kjkj' =~ /(\d)/) > 5)The assignment to $start happens, but the list ($start) has just one element.
If you insist on writing a complicated expression instead of breaking things into pieces, you can take advantage of the comma operator:
if ((($start) = '6kjkj' =~ /(\d)/), $start > 5) { print "Why isn't this printing? 6 is greater than 5."; }As Sam Choukri points out in the comments,
if (('6kjkj' =~ /(\d)/) and ($1 > 5)) {is safer, and simpler, than both alternatives that first came to my mind.
更多推荐
发布评论