Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Array of Hashes to Hash of arrays for SQL::Abstract

by kcott (Archbishop)
on Mar 19, 2020 at 07:46 UTC ( [id://11114456]=note: print w/replies, xml ) Need Help??


in reply to Array of Hashes to Hash of arrays for SQL::Abstract

G'day Skeeve,

"Is there a better way to achieve this transposition?"

The following code generates a list of unique keys once and doesn't require initialisation of %columns. Note that the source data I've used contains existent and non-existent keys along with defined and undefined values; for future reference, please consider providing more representative data in your OP.

#!/usr/bin/env perl use strict; use warnings; use Data::Dump; my $data = [ { a => 1 }, { a => 3, b => 4 }, { }, { b => 8 }, { a => undef, c => 9 }, ]; my (%columns, %seen_key); my @uniq_keys = grep !$seen_key{$_}++, map keys(%$_), @$data; for my $row (@$data) { push @{$columns{$_}}, $row->{$_} for @uniq_keys; } dd \%columns;

That outputs:

{ a => [1, 3, undef, undef, undef], b => [undef, 4, undef, 8, undef], c => [undef, undef, undef, undef, 9], }

If you want something other than undef to represent your null values — a zero-length string for instance — you can change the push to this if you have Perl 5.10 or later:

push @{$columns{$_}}, $row->{$_} // '' for @uniq_keys;

For older versions of Perl, you can use this:

push @{$columns{$_}}, defined($row->{$_}) ? $row->{$_} : '' for @uniq_ +keys;

Both of those produce identical output:

{ a => [1, 3, "", "", ""], b => ["", 4, "", 8, ""], c => ["", "", "", "", 9], }

As a side note, code like this:

my $sql= new SQL::Abstract( array_datatypes => 1 );

is discouraged and it is recommended that it be avoided. See "perlobj: Indirect Object Syntax" for details, paying particular attention to the opening, emboldened text:

"Outside of the file handle case, use of this syntax is discouraged as it can confuse the Perl interpreter. See below for more details."

A better way to write that statement would be:

my $sql = SQL::Abstract::->new(array_datatypes => 1);

— Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11114456]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-03-28 16:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found