Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

unset arbitrary associative array element



Hi,

one can set an arbitrary associative array element with:

typeset -A hash
hash[$key]=$value

But:

unset "hash[$key]"

Doesn't work for values of $key that contain "]" or "\" (or
characters whose encoding contain the bytes 0x5c or 0x5d) or for
an empty $key.

hash[$key]=()

doesn't work ("attempt to set slice of associative array"
error).

unset "hash[${key//(#m)[]\\]/\\$MATCH}]"

addresses keys with "]" and "\" but not those with characters
whose encoding contains 0x5c/5d or the empty key.

Is there any other way, other than recreating the full array
with something like:

hash=("${(@kv)hash[(I)^$key]}") # untested

ksh93 has the same kind of issues (plus various bugs for
characters that contain 0x5c/5d bytes), but supports unset
"hash[]" (even though like zsh it doesn't support hash[]=value).

In bash, one can do:

unset 'hash[$key]'

That is, the argument is evaluated as shell code! That means we
can unset arbitrary elements that way (though note that bash
doesn't support hash elements with empty keys!), but I would not
want to go there for bash as that means that things like

unset "hash[$key]"

are command injection vulnerabilities.

Not sure what's the best way to address it. Maybe like for
typeset and co, make "unset" a keyword where in

unset hash[$key]

That a[$key] is parsed the same way as in

hash[$key]=value

Or maybe a:

unset -k "$key" hash

Or

hash+=("$key") # add element without a value removes the element

In any case, it would be useful if we could set or unset the
element with the empty key with:

hash[]=value
unset "hash[]"

-- 
Stephane



Messages sorted by: Reverse Date, Date, Thread, Author