Re: equality as a variable



Brian Wakem <no@xxxxxxxxx> wrote in news:3q58ibFd6ikpU1@xxxxxxxxxxxxxx:

> Shiraz wrote:
>
>> i need to put the equality in an if statement as a variable
>>
>> ($val1, $val2, $comp) = (1,2,"gt");
>> if ($val1 $comp $val2)
>> { print $val1; }
>> i couldnt find anything in the achives.... if some knows it, please
>> let me know.. or point me in a direction i can research the method.
>> thanks
>
>
> if (eval("$val1 $comp $val2")) {
> ...
> }
>

Hmmm ... Sorry, I am going to go with hash based solution:

#!/usr/bin/perl

use strict;
use warnings;

use Carp;

my %handlers = (
'>' => sub { $_[0] > $_[1] },
'<' => sub { $_[0] < $_[1] },
'>=' => sub { $_[0] >= $_[1] },
'<=' => sub { $_[0] <= $_[1] },
'==' => sub { $_[0] == $_[1] },
'!=' => sub { $_[0] != $_[1] },
'<=>' => sub { $_[0] <=> $_[1] },
);

sub do_compare_op {
my ($v1, $op, $v2) = @_;
my $handler = $handlers{$op};
croak "Undefined op: $op" unless defined $handler;
return 0 + $handler->($v1, $v2);
}

my %examples = (
'5 == 6' => [ 5, '==', 6 ],
'5 <= 6' => [ 5, '<=', 6 ],
'5 <=> 6' => [ 5, '<=>', 6 ],
);

for my $x (keys %examples) {
print "$x: ", do_compare_op(@{ $examples{$x} }), "\n";
}

__END__

C:\Documents and Settings\asu1\My Documents> perl t.pl
5 == 6: 0
5 <=> 6: -1
5 <= 6: 1
.