in reply to Simple Hash problem

The simplest way is with a single loop:

foreach my $k (@mips) { $hash{$k} = 999 unless exists $hash{$k}; }
This might even touch off a round of golf...

HTH

Replies are listed 'Best First'.
Re: Re: Simple Hash problem
by Vavoom (Scribe) on Feb 08, 2002 at 20:41 UTC
    It is simple, but it doesn't quite match the sample results. This approach ignores elements in %hash that are not in @mips, whereas the original example removed them.

    Here's a small rework that fixes it:
    my %newhash = (); for (@mips) { $newhash{$_} = $hash{$_} || 999; } %hash = %newhash;

    lestrrat's solution is much more fun to look at, though.

    Vavoom
      I am not following why you needed to create the temp hash. My output appears to be correct for the example given with the following line of code.

      for(@mips){$hash{$_}||=999}

      UPDATE:
      Thanks crazyinsomniac, after reading these posts several times and talking with you in CB I realize that the example above did not have G in it once it was processed. I read the question and did not examine the output. In the text of the original question it does not state that missing keys should be removed, it merely states that the values should be 999 if they have none.
Re: Re: Simple Hash problem
by particle (Vicar) on Feb 08, 2002 at 20:47 UTC
    okay, i'll bite... (41 chars--surely it can be done in less?)

    map{exists$hash{$_}or$hash{$_}=999}@mips

    update: (39 chars)

    exists$hash{$_}or$hash{$_}=999for@mips
    update2: vavoom is right. back to the drawing board... (75 chars--results in %h, and it's a little obfuscated)

    @$_{@mips}=(999)x@mips for\my%h;exists$hash{$_}and$h{$_}=$hash{$_}for@ +mips;

    ~Particle