开发者

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 -

eva开发者_StackOverflow中文版l "\$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.


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)


Are you sure you wouldn't rather do something like:

my $href;
my $somevar = 8;
$href->{foo} = sub { $somevar * 4 };
my $var = $href->{foo}->();

If you're not sure whether $href->{foo} is a scalar, code ref, etc, you can check it with the ref() function, or better, with Scalar::Util::reftype().


Change the hash key to be "function( 0.01 * ($another_var // 0) )"

$another_var // 0 is equivalent to defined($another_var) ? $another_var : 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜