user2521358
user2521358

Reputation: 289

How do i interpret this if statement

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

what is the above logic in Perl? I've never seen an if condition like this in other languages. $2 and $3 are just capturing groups of some regex.

or this:

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

Upvotes: 2

Views: 149

Answers (2)

RobEarl
RobEarl

Reputation: 7912

In Perl, a variable evaluates to true if it is defined, non-zero (*see special cases in amon's comment) and non-empty. The final condition is redundant as $3 can't evaluate to true and be 0.

The code is simply ensuring that capture groups 2 and 3 captured something.

Also see: How do I use boolean variables in Perl?

Upvotes: 8

user1558455
user1558455

Reputation:

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

Means, if $2 and $3 are successfull captured and $3 is not 0

So $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.

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

Just Means the same, but the 2nd and the 3rd match need to be 0.

$line = '5 0 0 4';

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

Upvotes: 5

Related Questions