Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warnings in Perl Eval

I need to hide warnings within eval but the rest of the code should continue to throw warning messages. Here is what I have -

eval "\$value = $hash->{key}";

now value of $hash->{key} could be a function call, like:

$hash->{key} = "function(0.01*$another_var)";

The problem comes when $another_var is undef (or ""). The script just craps out with the following message -

Argument "" isn't numeric in multiplication (*) at (eval 1381) line 1.

Any suggestions how I can avoid this? One option i was thinking was to parse the value inside parenthesis and evaluate that first, but its quite complex with the data I am dealing with.

like image 721
user589672 Avatar asked Jan 25 '11 20:01

user589672


People also ask

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.

What does eval do in Perl?

The eval function takes a character string, and evaluates it in the current perl environment, as if the character string were a line in the currently executing perl program.

What does Perl eval return?

In both forms, the value returned is the value of the last expression evaluated inside the mini-program; a return statement may also be used, just as with subroutines. The expression providing the return value is evaluated in void, scalar, or list context, depending on the context of the eval itself.


1 Answers

Wrap your code in a no warnings block.

...
{
    no warnings;
    eval "\$value = $hash->{key}";
}
...

You can also disable specific classes of warnings. See perllexwarn for the hierarchy of warning categories and perldiag for the category that any particular warning belongs to.

{
    no warnings qw(uninitialized numeric);
    eval "\$value = $hash->{key}";
}

(blah blah blah standard disclaimer that any one who would disable warnings is unfit to get within 25 feet of an adding machine blah blah)

like image 185
mob Avatar answered Sep 23 '22 14:09

mob