Vaibhav Agarwal
Vaibhav Agarwal

Reputation: 1144

Perl: Difference in code

I am new to Perl and I am trying to find the difference between two snippets:

$string && $string eq 'foo'
$string eq 'foo'

I tried several conditions but I am not able to find the difference. Can somebody help me identify the difference?

Upvotes: 3

Views: 132

Answers (1)

toolic
toolic

Reputation: 62037

One difference is that the 2nd line could generate a warning message (when using use warnings;) if the variable has never been assigned a value:

use warnings;
use strict;

my $string;

if ($string && $string eq 'foo') {
    print "true1\n";
}
else {
    print "false1\n";
}

if ($string eq 'foo') { # Get warning
    print "true2\n";
}
else {
    print "false2\n";
}

The warning message is:

Use of uninitialized value $string in string eq

Upvotes: 12

Related Questions