Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Adding missing values into a hash

by sundialsvc4 (Abbot)
on Jun 19, 2014 at 13:40 UTC ( #1090466=note: print w/replies, xml ) Need Help??

in reply to Adding missing values into a hash

Also, in general, here’s a way to introduce missing keys into a hash:   (extemporaneous coding, might not compile)

foreach my $key (qr/AA BB CC/) { $myrecord->{$key} = 'NA' unless exists($myrecord->{$key}); }

You would do this after the loop that built the hash from the inputs.   Two things to note here:

  1. The unless suffix might be new to you, but it’s very handy in situations exactly like this . . .
  2. The use of the function exists() is very important, because you really do want to know whether the key exists in the hash, regardless of whether its value (if present) would evaluate to True or to False.  

This logic will loop through the list of keys (AA, BB, CC), and insert the value 'NA' for each of them if they’re not there.

Obviously, this is not the only way to do it.   For instance, you might not want to corrupt the value of the hash by sticking NA strings into it, so you might instead copy the values to another hash (initialized to empty-hash before the start of the loop).   The code would use an if statement instead of unless, but it would still use exists() as shown.   Such logic could be used, with a known-complete list of all keys that could occur, to copy only those keys into an output hash, inserting NA into that hash for any missing values.   If you for any reason do not want to trust that the source-hash in question contains only keys that you are interested in, that would be one way to accomodate that.

Replies are listed 'Best First'.
Re^2: Adding missing values into a hash
by LanX (Bishop) on Sep 29, 2017 at 21:18 UTC

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1090466]
[Discipulus]: good morning community!
[Corion]: Good morning Discipulus!

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2018-06-19 07:08 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (111 votes). Check out past polls.