Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Difference in code

Tags:

operators

perl

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?

like image 290
Vaibhav Agarwal Avatar asked Apr 30 '26 13:04

Vaibhav Agarwal


1 Answers

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
like image 185
toolic Avatar answered May 03 '26 15:05

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!