Jonathan Dewein
Jonathan Dewein

Reputation: 984

Copy array to hash

I'm trying to copy an array to a hash, such that each element of the array is a key, followed by an empty value.

my %questions = map { @u_list => $_ } @u_list;

This only prints out

=>

I see on perldoc this idiom:

     %hash = map { get_a_key_for($_) => $_ } @array;

But I cannot figure out how to set the keys. I want the keys to be each element in the array.

Upvotes: 2

Views: 2381

Answers (5)

hwnd
hwnd

Reputation: 70732

Here are a few different ways to do this, just for reference.

Using map

my %questions = map { $_, undef } @u_list;

Using a foreach

my %questions;
$questions{$_} = undef foreach ( @u_list );

Using a hash slice.

my %questions;
@questions{@u_list} = (undef) x @u_list;

Upvotes: 1

drwww
drwww

Reputation: 85

$_ is the current element of your list @u_list.

So you have to say

my %questions = map { $_ => 1 } @u_list;

to map your list elements as hash keys.

Upvotes: 2

AMADANON Inc.
AMADANON Inc.

Reputation: 5929

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

This sets the values to an empty string

Upvotes: 3

kjprice
kjprice

Reputation: 1322

my %questions = map { $_ => undef } @u_list;

In the map, each element of @u_list gets set to $_.

Upvotes: 8

evil otto
evil otto

Reputation: 10582

Super confusing but functional answer:

@questions{@u_list}=();

This is using the hash slice syntax to specify a set of hash keys..

Upvotes: 10

Related Questions