in reply to How to do that with eval ?

So are there any more efficient way to do that ?

A better question might be is using eval the most inefficient , least secure and most incomprehensible method? To which the answer is yes.

Now seriously string eval and user input or even file input is a recipe for disaster. As you currently don't seem to understand why or how all I can do is suggest you avoid eval "this" until you understand how dangerous it really is.

If you were to outline what you are actually trying to do (as opposed to how do I take this loaded gun, put it to my head and wait for someone to pull the trigger ;-) I am sure you will find lot's of efficient, secure and fast suggestions.

From the information you give the if/elsif/elsif/else structure you show IS the most efficient structure in terms of speed and security. There are many other ways to do it, typically a dispatch hash, but these are all slower. Just about anything will be more secure than a string eval where you let user input in.

my %dispatch = ( '>' => sub { $_[0] > $_[1] }, '<' => sub { $_[0] < $_[1] }, '=='=> sub { $_[0] == $_[1] }, ); # now in loop if ( $dispatch{$sop} ) { # OK so $sop exists, get the right function from # the dispatch hash and call it with the args we want if ( &{$dispatch{$sop}}( $tmpdata[8], $sport ) ) { # yabada } else { # ! yabada } } else { die "Illegal op $sop. Are you trying to hack me?\n"; } # end loop

cheers

tachyon

Replies are listed 'Best First'.
Re: Re: How to do that with eval ?
by tilly (Archbishop) on Apr 10, 2004 at 11:39 UTC
    Just to be clear, an if/elsif/elsif/.../else structure is typically faster than a dispatch hash, but doesn't scale as well to large numbers of possibilities. Scalability is like an 18-wheeler, great for doing a lot with lots of data, but for daily use the sports car is likely faster and loads more fun.

    A better reason to use a dispatch hash is because you prefer how it lets you organize a piece of code.

Re: Re: How to do that with eval ?
by ihb (Deacon) on Apr 10, 2004 at 17:56 UTC

    my %dispatch = map { $_ => eval sprintf 'sub { $_[0] %s $_[1] }', $_ } qw/ < <= == >= > /;

    Just to abstract it one more level (and get to use eval() constructively again). :-)

    (There's a possibility that I'd do this in real code since I've become such an OAOO-junkie. Am I being a bit extreme here? (I usually needn't bother about speed efficiency.))

    ihb