Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my eval wrong or do I not understand eq vs == in Perl

Tags:

perl

I am having trouble understand eval or maybe I do not understand eq vs ==. 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]

One would think that you'd get ...

[cat eq cat]
rc is [1]

... since "cat" equals "cat", right?

like image 999
Red Cricket Avatar asked Nov 29 '22 10:11

Red Cricket


1 Answers

Others have pointed out the root of your problem. I am going to recommend you avoid using string eval for this purpose. Instead, you can use a 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,=
like image 76
Sinan Ünür Avatar answered Dec 06 '22 09:12

Sinan Ünür