Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
$exeif= "!exists ( $hash{key} )";

I have a string which is to check the existence of a key in a hash. I would need to execute this on a run time ( like eval does ). But I have tried this with eval. it doesnt work.

I would need to execute and get the result ( exists of not exist). Could any one please advice?

Replies are listed 'Best First'.
Re: Dynamic execution of expression
by moritz (Cardinal) on Aug 18, 2011 at 11:51 UTC
    If the !exists ( $hash{key} ) is actually a literal in your program (and not user input), it's probably better to implement that with code references:
    my %hash; my $condition = sub { ! exists $hash{key} }; # and later on use it as if ($condition->()) { print "'key' does not exists in \%hash\n"; }
Re: Dynamic execution of expression
by muba (Priest) on Aug 18, 2011 at 11:22 UTC

    Nope, because when you put variables inside double-quoted strings, they get interpolated. This is something you should already know, as you would use it in common statements such as print "The value is $value. The dog's name is $dog{name}. The third element is $elements[2]."

    See this:

    use strict; use warnings; my %hash = ( foo => "bar", bar => "baz" ); sub testAndExec { my $cond = shift; if (eval $cond) { print "This is executed!\n"; } else { print "Not executing this time.\n"; } print "But there was an error:\n $@" if $@; print "\n"; } my $exeif = "!exist $hash{foo}"; print "Double quotes, existing key: <$exeif>\n"; testAndExec $exeif; $exeif = "!exist $hash{foo}"; print "Double quotes, existing key: <$exeif>\n"; testAndExec $exeif; $exeif = '!exists $hash{bar}'; print "Single quotes, existing key: <$exeif>\n"; testAndExec $exeif; $exeif = '!exists $hash{baz}'; print "Single quotes, non-existing key: <$exeif>\n"; testAndExec $exeif;

    Output:

    Double quotes, existing key: <!exist bar> Not executing this time. But there was an error: Can't locate object method "exist" via package "bar" (perhaps you +forgot to load "bar"?) at (eval 1) line 1. Double quotes, existing key: <!exist bar> Not executing this time. But there was an error: Can't locate object method "exist" via package "bar" (perhaps you +forgot to load "bar"?) at (eval 2) line 1. Single quotes, existing key: <!exists $hash{bar}> Not executing this time. Single quotes, non-existing key: <!exists $hash{baz}> This is executed!

    Update: fixed a logical flaw spotted by AnomalousMonk. Thanks.