Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Adding values from an array to a hash

by PerlingTheUK (Hermit)
on Oct 12, 2006 at 10:08 UTC ( #577794=perlquestion: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://577794]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (9)
As of 2023-12-05 12:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?











    Results (27 votes). Check out past polls.

    Notices?