在我的程序中,我將一個file names
的列表從命令行傳遞到我的程序,並檢查每個文件是否爲 - executable
,readable
和writable
..如果`foreach-when`語句中最後一個'when`語句爲false時,總是執行默認語句
我使用foreach-when
語句上述問題。但似乎有在使用when
和default
聲明,這可能是我沒有使用正確的一些問題,但其捐贈我意想不到的結果..
這是我的代碼: -
#!/perl/bin
use v5.14;
use warnings;
foreach (@ARGV) {
say "*************Checking file $_ *******************";
when (-r $_) { say "File is Readable"; continue; }
when (-w $_) { say "File is Writable"; continue; } # This condition is true
when (-x $_) { say "File is Executable" } # This condition is false
default { say "None of them" } # Executed
}
我添加了一個continue
,只有前兩個when
使perl的檢查所有條件而不考慮文件的名稱..
另外,我還沒有添加continue
到倒數第二when
,因爲我只希望我的default
如果執行沒有when
要執行..
這裏的問題是,如果最後when
條件爲假,它不會進入塊,和然後它繼續執行default
即使我的前兩個when
語句得到滿足。
我檢查這個問題的原因,通過改變我的when
的順序,看到如果只有最後when
被執行時,它會看到沒有continue
,因此它不會執行default
聲明。 。
所以,在上面的代碼,我已經換-x
和-r
..我的文件是可讀的,所以最後when
在這種情況下會被執行..然後不執行我的default
聲明..
#!/perl/bin
use v5.14;
use warnings;
foreach (@ARGV) {
say "*************Checking file $_ *******************";
when (-x $_) { say "File is Executable"; continue; }
when (-w $_) { say "File is Writable"; continue; }
when (-r $_) { say "File is Readable" } # This condition is true
default { say "None of them" } # Not executed
}
所以,我想問一下,如何處理這種情況..我希望它能像Perl的語句被添加到given-when
聲明一樣工作..
它應該檢查所有的when
,並跳過default
如果在至少一個when
執行..
爲什麼ü選擇「當」了一個簡單的「如果」在這種情況下語句? – snoofkin
@ soulSurfer2010 ..因爲我正在閱讀一本書,它正在練習'given-when'的章節。我正在學習Perl,所以我想學習不同的方法來解決問題。當然,這個可以使用一組if if .. –
我想,沒有使用given-when構造一段時間,繼續將按照您預期的那樣在給定構造中應用,而不僅僅與'when'一起使用時,只是猜測 – snoofkin