in reply to Using dynamic operators in an if() statement

I think what you're looking for is a string eval, which would be something like this:
if (eval "\$consumption $operator")

But I wouldn't recommend you do that. It means any errors in $operator will be runtime instead of compile-time errors, and that code will be re-compiled every time through your loop, which is bad for performance.

Instead, consider customizing your condition with a small sub, something like:

sub process_match { my($consumption)=@_; return $consumption > 98.0; } if (process_match($consumption)) { do something; }
This gives you the same flexibility without any of the downsides of string eval.

Good luck!

Update: $consumption should be escaped in eval. Thanks, ikegami!

Replies are listed 'Best First'.
Re^2: Using dynamic operators in an if() statement
by VSarkiss (Monsignor) on Aug 22, 2006 at 15:06 UTC

    Yes, this is a very good approach. To expand on it, you could even dispatch to multiple selection functions based on other criteria (the OP doesn't make clear what the criteria are, but hints at them). Something like this (untested) example:

    my %match = ( high => sub { $_[0] > 98.0 }, low => sub { $_[0] < 55.0 }, exact => sub { $_[0] = 77.0 }, ); # ...later... my $test = decide_somehow(); if ($match{$test}->($consumption)) { print "Test $test succeeded\n"; do_something(); };
    There are other ways to generalize the approach; this is just an example that may or may not be appropriate, depending on other program constraints.