eval

时间:2023-03-09 14:25:14
eval
字符串形式:表达式计算

Vsftp:/root/perl/14# cat aa
9
5
1
2
Vsftp:/root/perl/14# cat a1.pl
open (A,aa); while ($line = <A>){
chomp $line;
$str .=$line; ##将所有的行连接起来
print "\$str is $str\n";
};
print "11111111\n";
eval $str;
Vsftp:/root/perl/14# perl a1.pl
$str is 9
$str is 95
$str is 951
$str is 9512
11111111 ##在$str 中放入一些代码
Vsftp:/root/perl/14# cat a2.pl
$str='$c=$a+$b';
$a=10;$b=20;
eval $str;
print $c;
print "\n";
Vsftp:/root/perl/14# perl a2.pl
30 Vsftp:/root/perl/14# cat a3.pl
eval ( 5 / 0 );
print $@;
print "\n"; Vsftp:/root/perl/14# perl a3.pl
Illegal division by zero at a3.pl line 1. Perl会将错误信息放入一个称做$@的变量中 代码块形式:例外处理 在这种形式下,eval 后面跟的是一个代码块,而不再是包含字符串的标量变量 Vsftp:/root/perl/14# cat a3.pl
eval { $a=10;
$b=0;
$c=$a/$b;
print "1111111111\n";
};
print $@;
print "\n"; Vsftp:/root/perl/14# perl a3.pl
Illegal division by zero at a3.pl line 3. Vsftp:/root/perl/14# 在编译脚本时,Perl 对代码块进行语法检查并生成编译代码,在遇到运行错误时, Perl 将跳过eval块中剩余的代码,并将$@设置为相应的错误信息。 /**********没有eval 和有eval的区别: Vsftp:/root/perl/14# cat a3.pl
{ $a=10;
$b=0;
$c=$a/$b;
print "1111111111\n";
};
print $@;
print "\n"; print "2222222222222222\n";
Vsftp:/root/perl/14# perl a3.pl
Illegal division by zero at a3.pl line 3. 此时程序直接中断,没有继续运行 Vsftp:/root/perl/14# cat a3.pl
eval { $a=10;
$b=0;
$c=$a/$b;
print "1111111111\n";
};
print $@;
print "\n"; print "2222222222222222\n";
Vsftp:/root/perl/14# perl a3.pl
Illegal division by zero at a3.pl line 3. 2222222222222222 加上eval后程序出错,但是下面代码继续运行 为了产生自己的错误,你需要使用die,Perl 知道某一段代码是否在eval 块中执行,因此, 当die 被调用时,Perl只是简单的将错误信息复制给全局变量$@,并跳转到紧跟eval块的语句继续执行。 Vsftp:/root/perl/14# cat a3.pl
eval { $a=10;
$b=0;
open (F,"xx22") ;
print "1111111111\n";
};
print $@;
print "\n"; print "2222222222222222\n";
Vsftp:/root/perl/14# perl a3.pl
1111111111 2222222222222222 Vsftp:/root/perl/14# cat a3.pl
eval { $a=10;
$b=0;
open (F,"xx22") or die "xx22 $! ";
print "1111111111\n";
};
print $@;
print "\n"; print "2222222222222222\n";
Vsftp:/root/perl/14# perl a3.pl
xx22 No such file or directory at a3.pl line 3. 2222222222222222 Java/C++ 程序员肯定认出了它们与throw,try 和catch 的相似之处 try 对应于eval块,catch 对应于$@检查,而throw 对应die