2

I have following array of arrays in Perl that are getting as multiple rows in database.

$arrayref = [
    [ 1, "name1",  "name2" ],
    [ 2, "name3",  undef ],
    [ 3, "name5",  "name6" ],
    [ 4, "name10", undef ],
];

I want to make this as an array of hashes like this

my @array = (
    { id => 1, name => "name1",  l_name => "name2" },
    { id => 2, name => "name3",  l_name => undef },
    { id => 3, name => "name5",  l_name => "name6" },
    { id => 4, name => "name10", l_name => undef },
);
1
  • 2
    Where do you get your data for your array? Is parsing it into a hash upstream (rather than converting it later) an option? Commented Aug 13, 2015 at 12:15

2 Answers 2

8

You can use map {} to transform array references to hash references,

my @cols = qw(id name l_name);

my @array = map { my %h; @h{@cols} = @$_; \%h } @$arrayref;

or

use List::MoreUtils qw( zip );

my @cols = qw(id name l_name);

my @array = zip(\@cols, @$arrayref);
Sign up to request clarification or add additional context in comments.

3 Comments

Oh that's very elegant. I like it.
yes it is. Thanks for that solution. The one i made was a lengthy code
While this solves the OP's immediate problem, @Borodin's answer solves the real issue.
8

I have following array of arrays in Perl that are getting as multiple rows in database

You are presumably calling

$sth->fetchall_arrayref();

If instead you use an empty anonymous hash as the first parameter

$sth->fetchall_arrayref( {} );

then DBI will return the data in the format you want as an array of hashes

The DBI documentation describes it here

If $slice is a hash reference, fetchall_arrayref fetches each row as a hash reference. If the $slice hash is empty then the keys in the hashes have whatever name lettercase is returned by default. (See FetchHashKeyName attribute.) If the $slice hash is not empty, then it is used as a slice to select individual columns by name. The values of the hash should be set to 1. The key names of the returned hashes match the letter case of the names in the parameter hash, regardless of the FetchHashKeyName attribute.

For example, to fetch all fields of every row as a hash ref:

$tbl_ary_ref = $sth->fetchall_arrayref({});

2 Comments

Could you add a link to the DBI documentation? I've never seen that feature.
@simbabque: Sure, but it's only the fetchall_arrayref documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.