eval的两个作用

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()

posted on 2012-06-15 09:52  perlman  阅读(1735)  评论(0编辑  收藏  举报

导航