字符串形式:表達式計算 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