您的位置:首页 > 其它

eval的两个作用

2012-06-15 09:52 134 查看
1 捕获错误

# Catch exception with eval
# This is an exception of divided by zero
# if errors happened, perl stores it in $@
# you should check $@ immediately after eval {} block
# Note, eval is a function, not a flow control clause
# you need to add ';' after the block
use strict;
use warnings;

eval {
return 2 / 0;
};

print $@ if $@;


2 动态代码

# Dynamic code with eval
# syntax: eval "code"
# The script will execute the code after eval in run time

use strict;
use warnings;

sub test {
my $num1 = 2;
my $num2 = 3;

foreach my $op (qw!+ - * /!) {
print "$num1 $op $num2 equals ";
print eval "$num1 $op $num2", "\n";
}
}

test()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: