Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Hash assignments using map

by johngg (Canon)
on Feb 24, 2007 at 18:16 UTC ( [id://601900]=note: print w/replies, xml ) Need Help??


in reply to Hash assignments using map

If you are trying to initialise a hash with four keys ("a" to "d") each with a value of 1 using map you need to pass your four keys into the map but pass eight things out the other side, 'a', 1, 'b', 1, 'c', 1, 'd', 1. This is because a hash with four key/value pairs will flatten to a list of eight elements. You can do it like this.

my @keys = qw{a b c d}; my %hash = map { $_ => 1 } @keys;

Your loop alternative could be written

my @keys = qw{a b c d}; my %hash; $hash{$_} ++ for @keys;

Another alternative is to use a hash slice

my @keys = qw{a b c d}; my %hash; @hash{@keys} = (1) x scalar @keys;

I hope this is of use.

Cheers,

JohnGG

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2024-04-25 12:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found