jpfarmer has asked for the wisdom of the Perl Monks concerning the following question:
I frequently find myself using hashes to modify the value of a variable when a hash entry exists, otherwise set it to something else. For example, if I'm looking for a name to go with an ID number, I'll check the hash for the ID number. If that fails, the name should be "unknown".
I traditionally have done something like this: my $var = $hash{'key'}; $var = "something" unless $var; although I have more recently switched to my $var = $hash{'key'} || "something";, which I like even better. However, I still find myself wondering if there is a more elegant solution.
So, I'm wondering, is there a way to alter the value returned if a hash lookup fails? or have I stumbled on the Best Solution to my problem?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Making a failed hash lookup return something other than undef
by sauoq (Abbot) on Nov 13, 2003 at 19:59 UTC | |
|
Re: Making a failed hash lookup return something other than undef
by davido (Cardinal) on Nov 13, 2003 at 19:59 UTC | |
by thelenm (Vicar) on Nov 13, 2003 at 20:09 UTC | |
by shenme (Priest) on Nov 13, 2003 at 20:33 UTC | |
|
Re: Making a failed hash lookup return something other than undef
by thelenm (Vicar) on Nov 13, 2003 at 20:04 UTC | |
|
Re: Making a failed hash lookup return something other than undef
by hardburn (Abbot) on Nov 13, 2003 at 19:58 UTC | |
|
Re: Making a failed hash lookup return something other than undef
by blokhead (Monsignor) on Nov 13, 2003 at 20:03 UTC |