in reply to interpolating a variable into an operator
While eval is the method that promises the easiest result, it also makes for ugly security holes and hard to track down bugs. I'd go with storing all the operators and their operations in a hash and then using that to calculate your operations:
my %bin_cmp = { 'eq' => sub { my ($l,$r) = @_; $l eq $r }, 'ne' => sub { my ($l,$r) = @_; $l ne $r }, '>' => sub { my ($l,$r) = @_; $l < $r }, '<' => sub { my ($l,$r) = @_; $l > $r }, }; my $op = 'ne'; my $left = "Hello"; my $right = "World"; if (not exists $bin_cmp{$op}) { die "Don't know what to do with '$op'"; }; my $compare = $bin_cmp{$op}; my $result = $compare->($left, $right); print "$left $op $right is " . ($result ? 'true' : 'false');
|
|---|