我編寫了簡單的代碼片段,用於處理在受限制的(我們需要root權限的情況下)打開文件時發生的錯誤 以下代碼工作正常並且出現錯誤作爲O/p在perl中打開文件時使用try/catch或eval進行錯誤處理
#!/usr/bin/perl
use strict;
use warnings;
use Try::Tiny;
my $file_name = "/var/log/test.txt"; # needs root permission to create file
if(open(HAN, ">$file_name")){
print "sucuessfully opened file \n ";
} else {
print "Error with if/else while openning file : $! \n";
}
O/p:
誤差的if/else在打開文件:權限被拒絕
當我使用try/catch語句或EVAL具有相同的代碼,並打開文件
try {
open(HAN, ">$file_name");
} catch {
print "Error with try/catch while opening file : $_ \n";
};
或
eval {
open(HAN, ">$file_name");
};
print " Error with eval while opening file : [email protected] \n";
它顯示在$無輸出_或$ @,這是爲什麼happing?
總是把'使用警告' – 2013-03-01 13:01:43
通常使用的語法是使用open()或死「$!」; – run 2013-03-01 13:06:21
@ run-thanks,我知道我們可以使用「$!」對於open(),但試圖探索用try..catch或eval來做到這一點。 – Ganesh 2013-03-01 13:50:57