Re: equality as a variable



A. Sinan Unur <1usa@xxxxxxxxxxxxxxxxxxx> wrote in comp.lang.perl.misc:
> 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] },
> );

I'd use the hash *and* eval:

my %handlers = map { $_ => eval "sub { \$_[0] $_ \$_[ 1] }" }
qw( > < >= <= == != <=>),
# qw( gt lt ge le eq ne cmp),
;

That string-eval is perfectly safe, everything comes from inside the source.

Anno
--
If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
.