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

I've read How do I push new data into an existing hash? but I have a followup question. I'm parsing lines which look like
akey some data bkey some more data
into the first word and the rest of the line. I want to use the first word as the key. Is there a shortcut to creating the new hash record other than saying $hash{$1}=$2;? Something along the lines of
push %hash, /(.+?)\s+(.+)$/;

Replies are listed 'Best First'.
Re: hashes
by japhy (Canon) on May 25, 2001 at 23:47 UTC
Re: hashes
by AidanLee (Chaplain) on May 26, 2001 at 00:01 UTC
    while I'm rather speechless at japhy's elegant solution, if the hash DOES already exist you'll have to do something more like this:
    my %hash # lets assume this already has stuff in it { my %tmp_hash = map /(\S+)\s+(.*)/, <FILE>; @hash{ keys %tmp_hash } = @tmp_hash{ keys %tmp_hash }; }
      If the hash does exist you could also do this:

      for (@ListOfData) { %hash = (%hash, /(\S+)\s+(.*)/); }
      ... but I have to wonder how fast that would be...

      --
      I'd like to be able to assign to an luser

        As you say, having to go through all the items in %hash each time you add a key is definitely _not_ what you want in terms of speed. This is an _ok_ technique if you want to merge two arrays, as was I believe was pointed out in this node's discussion. However, this is best as a "once only" kind of deal.

      actually, for pre-existing hash, i'd combine japhy's with albannach's to get

      %hash = (%hash, (map /(\S+)\s+(.*)/, <FILE>));
      or i'd make the assignment part of the loop (which i'd change from map to for):
      for (<FILE>) {/(\S+)\s+(.*)/ && $hash{$1} = $2}
      ... which is what kwolters wanted to avoid.

      unfortunately, despite the fact that hashes can be coerced into arrays in most circumstances, you can't push onto them.

      caveat: i cut & pasted and was not able to test this. i hate being on the road and having my server go boom. .

      .