Filling a hash with map and split...

I want to know if there is a way to take an array and split each of its values into a key value pair on some delimiting character and then map those into key/values for a hash.  Here is an example of the idea but it doesn't work...

@a = "ONE:1","TWO:2";


      %hash = map {split(/:/, $_)} @a;

This would yield:

$hash{ONE} = 1;

$hash{TWO} = 2;

But it doesn't.  I know I can break this into a couple of steps with a loop but I resist especially since I think I've seen this done before... Any ideas?

Thanks!
LVL 3
guadalupeAsked:
Who is Participating?
 
dmagConnect With a Mentor Commented:
Your problem isn't in line 2, it's in line 1! The assignment

@a = "ONE:1","TWO:2";

Only assigns the first element. You need

@a = ("ONE:1","TWO:2");

And the 2nd line will work fine.

P.S. You can shorten it up to:

%hash = map { split /:/ } @a;
0
 
maneshrCommented:
try this piece from the command prompt. it should help you


#!/usr/local/bin/perl

@array=("ONE:1","TWO:2","THREE:3");


foreach(@array){
  @tmp=split(/:/,$_); ##  Break the element into ONE 1
  $num{$tmp[0]}=$tmp[1];  ##  Make ONE the key and 1 the value
}

foreach(sort keys %num){
  print $_," = ",$num{$_},"\n";
}
0
 
guadalupeAuthor Commented:
opps  its been along week (already)!

Thanks!
0
All Courses

From novice to tech pro — start learning today.