perl.beginners
[Top] [All Lists]

Re: Evaluate an operator given as a string

Subject: Re: Evaluate an operator given as a string
From: jwkrahn@xxxxxxx (John W. Krahn)
Date: Wed, 30 Jul 2008 13:36:59 -0700
Newsgroups: perl.beginners


Amit Koren wrote:
Hi all.

Hello,

I'm trying to pass the operators ">="  or "<="  to a subroutine,
and then use it inside an "if" statement.
What changes should i apply to the code below to make it work ?

my_evaluate ( ">=");

sub my_evaluate {
   my ($sign) = @_;
   my $x = 10;
   my $y = 20;
   if ($x $sign $y) { # want it to be treated as:  if ($x >= $y)
     ...do something...
   }
}

my $greater_than_or_equal_to = sub { $_[0] >= $_[1] )
my $less_than_or_equal_to    = sub { $_[0] <= $_[1] )


my_evaluate( $greater_than_or_equal_to );

sub my_evaluate {
   my ( $sign ) = @_;
   my $x = 10;
   my $y = 20;
   if ( $sign->( $x, $y ) ) { # want it to be treated as:  if ($x >= $y)
     ...do something...
   }
}



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.                            -- Larry Wall

<Prev in Thread] Current Thread [Next in Thread>