在 zsh 中,如何测试关联数组(又名散列 table)是否具有特定的 属性?
in zsh, how do you test if an associative array (aka hash table) has a certain property?
我想写一个函数,returns如果 属性 存在则为 0,如果不存在则为 1。
例如:
typeset -A hashtable
hashtable[a]='this is a valid element'
testprop hashtable[a] # returns 0
testprop hashtable[b] # returns 1
这可能吗?
参数扩展${+name}
几乎可以,随心所欲。如果 name
是一个设置参数 1
被替换,否则 0
被替换。
要获得所需的接口,可以将其包装到一个函数中:
function testprop {
case ${(P)+} in
0) return 1;;
1) return 0;;
esac
}
alias testprop='noglob testprop'
解释:
- 参数扩展标志
P
告诉 zsh 将值 </code> 解释为进一步的参数名称。 </li>
如果设置了 <code>name
, ${+name}
将被 1
替代,否则 0
。
- 别名 是必需的,这样
testprob
的参数就不需要引用了。否则索引周围的方括号将被解释为通配运算符。
我想写一个函数,returns如果 属性 存在则为 0,如果不存在则为 1。
例如:
typeset -A hashtable
hashtable[a]='this is a valid element'
testprop hashtable[a] # returns 0
testprop hashtable[b] # returns 1
这可能吗?
参数扩展${+name}
几乎可以,随心所欲。如果 name
是一个设置参数 1
被替换,否则 0
被替换。
要获得所需的接口,可以将其包装到一个函数中:
function testprop {
case ${(P)+} in
0) return 1;;
1) return 0;;
esac
}
alias testprop='noglob testprop'
解释:
- 参数扩展标志
P
告诉 zsh 将值</code> 解释为进一步的参数名称。 </li> 如果设置了 <code>name
, ${+name}
将被1
替代,否则0
。- 别名 是必需的,这样
testprob
的参数就不需要引用了。否则索引周围的方括号将被解释为通配运算符。