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?
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,=
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With