我如何解释这个if语句

use*_*358 2 perl

if ( $2 && $3 && $3 != 0 )
Run Code Online (Sandbox Code Playgroud)

Perl中的上述逻辑是什么?在其他语言中,我从未见过像这样的if条件.2美元和3美元只是捕获一些正则表达式的组.

或这个:

if ( $2 && $2 == 0 && $3 && $3 == 0 )
Run Code Online (Sandbox Code Playgroud)

Rob*_*arl 8

在Perl中,如果变量被定义,则变量的计算结果为true,非零(*参见amon注释中的特殊情况)和非空.最终条件是多余的,因为$3无法评估为真且为0.

代码只是确保捕获组2和3捕获了一些东西.

另请参阅:如何在Perl中使用布尔变量?

  • 在某些特殊情况下,最终条件并非多余.考虑字符串"0E0"和"0但是真",它们都是真的,尽管数字为零. (5认同)

小智 5

if ( $2 && $3 && $3 != 0 )
Run Code Online (Sandbox Code Playgroud)

意味着,如果2美元和3美元被成功捕获而3美元不是0

所以 $line = 'a b c 4';

$line =~ m/(\d)\s?(\d)\s?(\d)/;
# $1 is 4, $2 is undef, $3 is undef. Your if statement would fail.
$line2 = '3 4 5 6';
$line2 =~ m/(\d)\s?(\d)\s?(\d)/;
# $1 = 3, $2 = 4, $3 = 5. Your if statement is successfull.
Run Code Online (Sandbox Code Playgroud)

if ( $2 && $2 == 0 && $3 && $3 == 0 )

Just意思相同,但第二和第三场比赛需要为0.

$line = '5 0 0 4';

$line2 =~ m/(\d)\s?(\d)\s?(\d)/;
# $1 = 5, $2 = 0, $3 = 0. Your if statement is successfull.
Run Code Online (Sandbox Code Playgroud)