A. Sinan Unur <> wrote in comp.lang.perl.misc:
> (Anno Siegel) wrote in
> news:dhjufn$801$:
>
> > A. Sinan Unur <> wrote in comp.lang.perl.misc:
> >> Brian Wakem <> wrote in
> >> news::
> >>
> >> > Shiraz wrote:
> >> >
> >> >> i need to put the equality in an if statement as a variable
> ...
>
> >> Hmmm ... Sorry, I am going to go with hash based solution:
>
> ...
>
> > 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.
>
> I always type too much
)
It isn't just the laziness aspect, in fact the fewer lines of code may
take longer to write (and debug) than straight-forward typing of the
obvious. There is also reliability.
Basically, in the explicit definition of the hash you specify the same
thing twice which implies a possibility[1] of getting it wrong. Even
if the probability is minute, if you do this (programming) all day, it
is bound to happen once in a while, especially in maintenance. You're
safe from that when you specify each operator only once. The cost is
a possible loss in clarity.
Later you have more duplicate specifications:
# from memory
my %examples = (
'5 == 6' => [ 5, '==', 6],
'5 <= 6' => [ 5, '<=', 6],
# ...
);
In a similar vein, I wouldn't even use a hash for that, but specify a list
of strings:
my @examples = (
'5 == 5',
'5 <= 6',
'5 <=> 6',
'"E" eq "F"',
'"E" cmp "F"',
);
and run them as
print "$_: ", do_compare_op( split), "\n" for @examples;
with do_compare_op unchanged. That also shows them in the sequence
they are specified.
Anno
[1] initially mistyped "****ibility", was tempted to let it stand
--
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.