2
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 )
RobEarl
  • 7,862
  • 6
  • 35
  • 50
user2521358
  • 279
  • 1
  • 3
  • 11
  • can you show you code? – user1811486 Jul 03 '13 at 12:25
  • 1
    What other languages do you use? C, C++, Java, JavaScript accept the same expression (with appropriate variables for the language), and I'm sure Python and Ruby do too. The only language I can think of where this doesn't work as in Perl is BASIC and thus probably VB, and even then I'm not sure. – ikegami Jul 03 '13 at 13:38

2 Answers2

8

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?

Community
  • 1
  • 1
RobEarl
  • 7,862
  • 6
  • 35
  • 50
  • 5
    In some special cases, the final condition isn't redundant. Consider the strings `"0E0"` and `"0 but true"`, which are both true, despite being zero numerically. – amon Jul 03 '13 at 12:36
5
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.