| Deutsch English Français Italiano |
|
<ygao75szvb2.fsf@akutech.de> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!news.nobody.at!2.eu.feeder.erje.net!feeder.erje.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail
From: Ralf Fassel <ralfixx@gmx.de>
Newsgroups: comp.lang.tcl
Subject: Re: Array get element with default (no error if not exist)
Date: Fri, 16 Aug 2024 11:11:29 +0200
Lines: 41
Message-ID: <ygao75szvb2.fsf@akutech.de>
References: <962f50d6039d29a1bcdd98d8931988a3@www.novabbs.com>
Mime-Version: 1.0
Content-Type: text/plain
X-Trace: individual.net 2SOj6ud0n0LWWvYeHw9G/ACFd+9AR7IreQ4XwQUq0rQcuy9bs=
Cancel-Lock: sha1:b3XvmiTsGjL1cHsZPWdy+gRnuyk= sha1:EFxB0+RyEMITAJth8S5h9W093kM= sha256:eY8Lkdvvwb/yem8qe7uwF1tv+9rq/nAMahNsP2OM5HY=
User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Bytes: 1921
* RodionGork <rodiongork@github.com>
| Is there some motivation why some command for get-with-default is not
| implemented, e.g.
>
| puts [array peek $a 2 "default value"]
Most probably because up to now nobody required it so badly that s/he
implemented it, since the [info exists] approach is not too bad IMHO.
proc array_peek {arr key default} {
upvar $arr a
if {![array exists a] || ![info exists a($key)]} {
return $default
}
return $a($key)
}
array set a {1 one}
array_peek a 1 "default value"
=> one
array_peek a 2 "default value"
=> default value
Or you could set up a read-trace on the array to provide non-existing values:
array set a {}
trace add variable a read set_array_default
proc set_array_default {name1 name2 op} {
upvar a $name1
# puts stderr "set_array {$name1} {$name2} {$op}"
if {![info exists a($name2)]} {
set a($name2) "default"
}
}
set a(2)
=> default
Though that would alter the array and make the key exists which might
not be what you want.
HTH
R'