Re: equality as a variable
- From: "A. Sinan Unur" <1usa@xxxxxxxxxxxxxxxxxxx>
- Date: Fri, 30 Sep 2005 17:02:17 +0000 (UTC)
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
.
- Follow-Ups:
- Re: equality as a variable
- From: Brian Wakem
- Re: equality as a variable
- From: Anno Siegel
- Re: equality as a variable
- From: A. Sinan Unur
- Re: equality as a variable
- References:
- equality as a variable
- From: Shiraz
- Re: equality as a variable
- From: Brian Wakem
- equality as a variable
- Prev by Date: Re: equality as a variable
- Next by Date: Re: equality as a variable
- Previous by thread: Re: equality as a variable
- Next by thread: Re: equality as a variable
- Index(es):