http://www.perlmonks.org?node_id=577794

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

Dear Monks, I have just found a bug where a code was:
%locations = map{ $_ => 1 } ( @locations );
but should have done
%locations = map{ $_ => 1 } ( @locations, keys %locations );
Now I think that this setup is really annoying, easpecially as I would like rewrite it so that every value is counted to represent how often a location has been added. Is there a way to add onto the old hash instead of completely rewriting it?

Cheers,
PerlingTheUK

Replies are listed 'Best First'.
Re: Adding values from an array to a hash
by davorg (Chancellor) on Oct 12, 2006 at 10:10 UTC

    Do you mean this:

    $locations{$_}++ for @locations;
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Adding values from an array to a hash
by blazar (Canon) on Oct 12, 2006 at 10:29 UTC
    Now I think that this setup is really annoying, easpecially as I would like rewrite it so that every value is counted to represent how often a location has been added. Is there a way to add onto the old hash instead of completely rewriting it?

    I'm not really sure if I understand your question, but you probably either want

    %locations=(%locations, map {$_ => 1} @locations);

    or

    $locations{$_}++ for @locations;
Re: Adding values from an array to a hash
by reneeb (Chaplain) on Oct 12, 2006 at 11:27 UTC
    You can do this:
    @locations{@locations} = (1) x scalar @locations