Reputation: 984
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
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
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
Reputation: 5929
%hash = map { $_ => '' } @array;
This sets the values to an empty string
Upvotes: 3
Reputation: 1322
my %questions = map { $_ => undef } @u_list;
In the map, each element of @u_list
gets set to $_.
Upvotes: 8
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