kdubs
kdubs

Reputation: 1722

Perl create a hash from array that has the key and the value

I've got an example of what I'm trying to do below. It works, but I think it could be better. I've got an array that contains a key and a value in the same string delimited by a colon. I need to get that into a hash. currently I use split and a temp array. I feel I could get around that, but I can't quite find the syntax.

#!/grid/common/bin/perl -w
my @row=("x:3", "y:4", "z:abc");
my %hash = map { my @x=split(":",$_); $x[0] => $x[1] } @row;
print("$_ : $hash{$_}\n") for(keys(%hash));

Upvotes: 1

Views: 320

Answers (1)

Hunter McMillen
Hunter McMillen

Reputation: 61550

You can simply map the split operation across your array of key value pairs and assign that result back to a hash. perldoc -f split returns a list and you can assign a list directly to a hash:

my @row = ("x:3", "y:4", "z:abc");
my %hash = map { split /:/ } @row; # outputs "x", "3", "y", "4", "z", "abc"
print("$_ : $hash{$_}\n") for(keys(%hash));
# output
# z : abc
# y : 4
# x : 3

Upvotes: 6

Related Questions