Friday, June 10, 2011

Array to hash array example

use strict;
use warnings;

# for debugging
use Data::Dumper;

my @array = (
'ab cd ef',
'mn de fg',
);

my %hash;

for my $element (@array) {

if ($element =~ m{
^ # match the beginning of the
row
( \w{2} ) # match two characters
[ ] # match one space
(.*) # match the rest of the row
}mxs
) {
$hash{$1} = $2;
} else {
warn "error: incorrectly formatted array element: $element";
}

}

print Dumper \%hash;


OR


my %hash = map { split / ^ \S+ \K [ ]+ /x, $_ } @a;

See \K in perlre (5.10 or greater)

No comments: