using an array to set up hash keys

A

Adam Lawson

I would like to do the following:

@array qw(one two three four)


and make hash keys from @array and set each value to 1 so my hash would be

%hash (one => '1', two => '1' etc...

How can i do this?

Adam
 
J

John W. Krahn

Adam said:
I would like to do the following:

@array qw(one two three four)


and make hash keys from @array and set each value to 1 so my hash would be

%hash (one => '1', two => '1' etc...

How can i do this?

my %hash;
@hash{ @array } = ( 1 ) x @array;


my %hash = map { $_ => 1 } @array;


my %hash;
$hash{ $_ } = 1 for @array;



John
 
B

Brian McCauley

my %hash;
@hash{ @array } = ( 1 ) x @array;

my %hash = map { $_ => 1 } @array;

my %hash;
$hash{ $_ } = 1 for @array;

Don't forget

$_ = 1 for @hash{ @array };
 
U

Uri Guttman

BM> Don't forget

BM> $_ = 1 for @hash{ @array };

and if you will use exists to check for a key or know the keys are all true:

@hash{ @array } = @array;

only exists works with this . i think this is the fastest and i uses the
least ram. AKAIK missing hash values are marked with a flag and not a
full SV of undef. easily checked with a devel:: module so i leave that
as an exercise to the reader.

@hash{ @array } = () ;

of course you have to declare my %hash for both of those.

uri
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top