Re: equality as a variable
- From: anno4000@xxxxxxxxxxxxxxxxxxxxxxx (Anno Siegel)
- Date: 30 Sep 2005 18:00:23 GMT
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.
.
- Follow-Ups:
- 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
- Re: equality as a variable
- From: A. Sinan Unur
- equality as a variable
- Prev by Date: Re: website development and maintenance, using Perl. Please help!
- Next by Date: Re: I have problems with download scripts, it's trying to print instead of saving the file
- Previous by thread: Re: equality as a variable
- Next by thread: Re: equality as a variable
- Index(es):