這是關于 Perl 中函式的行為。
代碼片段:
&mmg();
my $count;
sub mmg {
&kkg();
print "symlink at location updated with the value\n";
$count ;
print "$count is value of count \n";
}
sub kkg {
if (-d "/home/PPP/ee/dir1") {
print "I got dir1\n";
my @arr = glob ("/home/PPP/YEP");
#..
#..... Some more commands
#..
return;
}
else {
sleep 5;
&mmg();
}
}
輸出:
symlink at builds location updated with the value of link at builds location
1 is value of count
symlink at builds location updated with the value of link at builds location
2 is value of count
symlink at builds location updated with the value of link at builds location
3 is value of count
symlink at builds location updated with the value of link at builds location
4 is value of count
symlink at builds location updated with the value of link at builds location
5 is value of count
symlink at builds location updated with the value of link at builds location
6 is value of count
在這里,“dir1”不存在,我在 30-35 秒后創建。現在,根據我的理解,在 30-35 秒后(創建 dir1 時),只有“構建位置的符號鏈接更新為構建位置的鏈接值 \n 1 是計數值”應該出現,即只有一次這些陳述句會列印出來的。但是,為什么這些要列印多次?
任何人都可以根據輸出行為幫助我理解這個概念嗎?我怎樣才能讓這個列印陳述句只列印一次?
我理解的概念:mmg() 會呼叫 kkg(),它會查看 dir1 是否存在。如果沒有,睡眠 5 次,然后再次呼叫 mmg()。mmg() 將再次呼叫 kkg(),依此類推,直到 dir1 出現。如果 dir1 可用,則 kkg() 將被回傳,并且 mmg() 繼續進行并且只列印一次里面的內容。
uj5u.com熱心網友回復:
這是您的代碼的執行:
&mmg();
&kkg();
if ...
else mmg();
&kkg();
if ...
else mmg();
&kkg();
if found! return to mmg()
print 1, sub finishes
print 2, sub finishes
print 3, sub finishes
因為每次檢查 dir1 是否存在時,都會啟動一個新的 mmg() 行程,并且每個行程都會在完成之前列印一次。因為它們是相互嵌套的。
你應該做的是只使用 kkg() 作為布林值,并讓 mmg() 處理回圈控制,例如:
sub mmg {
while (!kkg()) {
sleep 5; # do nothing
}
print "....";
# done
}
sub kkg {
if (-d "/home/PPP/ee/dir1") {
# do stuff
return 1; # true
}
return 0; # false
}
你甚至可能不需要 kkg()。
另外,您應該知道您使用的 sub 呼叫方法 -- &NAME()-- 不是慣用的方法。在perldoc perlsub中,您可以閱讀有關呼叫子例程的不同方式的資訊:
NAME(LIST); # & is optional with parentheses.
NAME LIST; # Parentheses optional if predeclared/imported.
&NAME(LIST); # Circumvent prototypes.
&NAME; # Makes current @_ visible to called subroutine.
你應該使用NAME().
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/450446.html
標籤:perl
