bradcathey has asked for the wisdom of the Perl Monks concerning the following question:

I thought this would be covered in the Q&A, but either it was overlooked or simply impossible or unnecessary. Never-the-less, it's bugging me.

Is it possible to add the key and value to a hash at the same time? I know the accepted way is:

my %info = ( address => '123 Main', city => 'Anytown' ); $info{name} = "Bill";

And even though the following won't work, it illustrates what I would like to do:

%info .= ( name => 'Bill' ); OR push ( %info, 'name' => 'Bill' );

Why? Clarity and perceived ease of populating a hash. Thanks for your comments.


—Brad
"The important work of moving the world forward does not wait to be done by perfect men." George Eliot

Replies are listed 'Best First'.
Re: Adding to a hash?
by davido (Cardinal) on May 19, 2005 at 00:38 UTC

    I understand what you're trying to do, but you just can't... not like that. Sometimes however, it's helpful to use a hash slice:

    my %hash = ( this => 1, that => 2 ); @hash{ qw/ those these / } = ( 3, 4 );

    The list of keys can be anything that resolves to a list, including an array or a subroutine call so long as it's properly disambiguated so as not to look like a bareword key.

    If the object is to add a whole bunch of new elements at once, that's where slices can be quite helpful.


    Dave

      This is also supports my methods which do require adding lots of pairs at different times. Great solution. Thanks.


      —Brad
      "The important work of moving the world forward does not wait to be done by perfect men." George Eliot
Re: Adding to a hash?
by Zaxo (Archbishop) on May 19, 2005 at 00:37 UTC

    Here's the simplest way: %info = (%info, name=> 'Bill'); By changing order you can control what overwrites what.

    After Compline,
    Zaxo

Re: Adding to a hash?
by Fletch (Bishop) on May 19, 2005 at 00:36 UTC

    Not that I see how it's any "clearer" than a simple assignment, but you could always keep your key/value pairs in an @array and use push @array => name => "Bill" (then %hash = @array when you're all done).

    Update: And another similar kinda crazy idea: store everything in a scalar in YAML format. Append new values onto to the scalar and then YAML::Load the result when you need the hash.

    use YAML (); my $data = "--- #YAML/1.0\n"; $data .= <<'EOT'; somekey: somevalue otherkey: othervalue EOT; $data .= "zorch: wubba"; my $hash = YAML::Load( $data );

      Hey, thanks. And believe or not, that meets my bizarre 'clarity' requirement.

      Clarity is like beauty, all in the eye of the beholder. But my question was an honest one.


      —Brad
      "The important work of moving the world forward does not wait to be done by perfect men." George Eliot