Why "bob" == "godzilla" in Perl?

In a Perl class today, a student included an assignment that annoys me. We are studying ARGV, but the result was not what I expected. His program (meme.pl) was:

#!/usr/bin/perl
$A = $ARGV[0];
chomp($A);
if ($A == "godzilla"){
    print "$A\n";
}
else {
    print "We need a monster name\n";
}

      

If I type:

% ./meme.pl bob

      

result

% bob

      

So the variable assignment works, but the condition ($ A == "godzilla") is true no matter what you type on the command line. I expected that since $ ARGV [0] is "bob" and $ A = $ ARGV [0], then it shouldn't be true that $ A = "godzilla".

What am I missing? I've been combing through this code for hours, and I know I'm just forgetting about some little thing.

+3


source to share


4 answers


Use eq

not ==

to test string equality:

if ($A eq "godzilla"){

      



More information is available at perldoc perlop .

Note. Adding use strict;

and use warnings;

to the beginning of your script would lead you in the right direction.

+15


source


use strict;

and use warnings;

should be enabled ... instant F in my book.

But no ... string evaluations using "==" evaluate all strings - except those that start with a number like "123bob" (see comment below) - as a numeric 0. That is why it evaluates to true - it " turns into a statement 0 == 0

. use warnings;

would say that there was something.

As many have said, use eq

for strings.

More evidence and options can be found here: (http://perlmeme.org/howtos/syntax/comparing_values.html)

Relevant excerpt (sample program):



#!/usr/bin/perl
use strict;
use warnings;

my $string1 = 'three';
my $string2 = 'five';

if ($string1 == $string2) {
    print "Equal\n";
} else {
    print "Not equal\n";
}

      

In the above example, you will get warning messages and both lines will evaluate to zero:

Argument "five" isn't numeric in numeric eq (==) at ./test.pl line 8.
Argument "three" isn't numeric in numeric eq (==) at ./test.pl line 8.
Equal

      


You don't get these warnings ... just "Equal", thanks to the lack of use warnings;

at the top of your - errr ... your student ... cough ... - code.;)

+11


source


When comparing strings, you must use "eq" instead of "==". So replace

($A == "godzilla")

      

by

($A eq "godzilla")

      

+6


source


What others say is correct to use eq

for string comparison. However, the test passes because when compared numerically with ==

"bob" and "godzilla" both evaluate to 0, so the test passes and you get bob

.

+5


source







All Articles