我正在尋找“最佳方式”或公認的 zsh 習慣用法來創建和使用可以回傳成功或失敗以及串列或其他文本值的函式。
目前我正在這樣做:
function happy
{
local happy_list=( a b c d )
if true ; then
echo $happy_list
return 0
else
return 1
fi
}
function sad
{
local sad_list=( a b c d )
if false ; then
echo $sad_list
return 0
else
return 1
fi
}
echo happy
if happy_result=( $( happy ) ) ; then
echo '$?:' $?
echo '$#happy_result' $#happy_result
echo '$happy_result' $happy_result
echo '$happy_list:' $happy_list
else
echo '!?!?!?!?'
fi
echo
echo sad
if sad_result=( $( sad ) ) ; then
echo '!?!?!?!?'
else
echo '$?:' $?
echo '$#sad_result' $#sad_result
echo '$sad_result:' $sad_result
echo '$sad_list:' $sad_list
fi
這導致
happy
$?: 0
$#happy_result 4
$happy_result a b c d
$happy_list:
sad
$?: 1
$#sad_result 0
$sad_result:
$sad_list:
有沒有更清潔的方法?特別是foo=( $( func ) )語法似乎可以改進,因為串列已經在 func 中創建。
版主更新:我相信現在這是這個問題的副本,我的首選答案(如果有人關心的話)就是這個答案。Meta 中的建議是關閉和合并。我不知道如何進行合并。版主可以幫我嗎?
uj5u.com熱心網友回復:
通常的習慣用法是在變數zsh中回傳標量結果,在陣列中回傳陣列結果:$REPLY$reply
all-files-in() {
reply=( $^@/*(ND) )
(( $#reply ))
}
if all-files-in /foo /bar; then
print -r there were files: $reply
else
print -ru2 there were none
fi
另一種方法是讓呼叫者指定存盤結果并使用的變數名稱eval或P引數擴展標志來進行間接賦值。
all-files-in() {
eval $1='( $^@[2,-1]/*(ND) )
(( $#'$1' ))'
}
if all-files-in files /foo /bar; then
print -r there were files: $files
else
print -ru2 there were none
fi
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/444668.html
