I am mistaken, or I do not understand eq vs == in Perl

I'm having trouble understanding eval, or maybe I do not understand eqvs ==. I have this short Perl script:

[red@tools-dev1 ~]$ cat so.pl
#!/usr/local/bin/perl -w
use strict;

while(<DATA>) {
    chomp;
    my ($arg1, $arg2, $op ) = split /,/;
    if ( $op eq '=' ) {
        $op = 'eq';
    }
    my $cmd = "$arg1 $op $arg2";
    print "[$cmd]\n";
    my $rc = eval $cmd || 0;
    print "rc is [$rc]\n";
}

__DATA__
cat,cat,=

When I execute it, I get:

[red@tools-dev1 ~]$ ./so.pl
[cat eq cat]
rc is [0]

You might think that you get ...

[cat eq cat]
rc is [1]

... since "cat" is equal to "cat", right?

+4
source share
5 answers

You use harsh words in strict mode, which is a mistake:

$ perl -e 'use strict; cat eq cat'
Bareword "cat" not allowed while "strict subs" in use at -e line 1.
Bareword "cat" not allowed while "strict subs" in use at -e line 1.
Execution of -e aborted due to compilation errors.

Whenever you evalstring, you should check $@to see if there was an error.

+7
source

Others have indicated the root of your problem. I am going to recommend that you avoid using strings evalfor this purpose. Instead, you can use the lookup table:

#!/usr/bin/env perl

use strict;
use warnings;

my %ops = (
'=' => sub { $_[0] eq $_[1] },
);

while(my $test = <DATA>) {
    next unless $test =~ /\S/;
    $test =~ s/\s+\z//;
    my ($arg1, $arg2, $op ) = split /,/, $test;
    if ($ops{$op}->($arg1, $arg2)) {
        print "'$arg1' $op '$arg2' is true\n";
    }
}
__DATA__
cat,cat,=
+8

, , .

my $cmd = qq{\$arg1 $op \$arg2};

eval

my %f = (
  "eq" => sub { my ($x, $y) = @_; $x eq $y },
  "==" => sub { my ($x, $y) = @_; $x == $y },
  # ..
);
# ..
$f{$op} or die "unknown $op";
my $rc = $f{$op}->($arg1, $arg2);
+3

my $cmd = "\$arg1 $op \$arg2";

$arg1 eq $arg2

$cmd

cat eq cat

use strict;. eval catch ($@), .


eval ?

my $rc;
if ($op eq '=') {
   $rc = $arg1 == $arg2;
} else {
   $rc = $arg1 eq $arg2;
}

my $rc = $op eq '=' ? $arg1 == $arg2 : $arg1 eq $arg2;

, .

+3

.. , script. eval :

eval cat eq cat || 0;

.

, $arg1 , $arg2, ?

$ = 0; $ rc = 1 if ($ arg1 eq $arg2);

0

All Articles