Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
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? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2022-07-03 04:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?