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

In most cases "better" is likely to be subjective. However, I would probably try to loop over $data just once:

use strict; use warnings; use Test::More tests => 1; my $data = [ {a => 1, b => 2}, {a => 3, b => 4}, {a => 5, b => 6} ]; my $want = { a => [1, 3, 5], b => [2, 4, 6] }; my %columns; for my $row (@$data) { for my $k (keys %$row) { $columns{$k} //= []; push @{$columns{$k}}, $row->{$k}; } } is_deeply \%columns, $want;

Replies are listed 'Best First'.
Re^2: Array of Hashes to Hash of arrays for SQL::Abstract
by Skeeve (Parson) on Mar 18, 2020 at 10:39 UTC
    However, I would probably try to loop over $data just once

    The disadvantage here is, that you might loose null-values due to missing keys in your data

    my $data = [ {a => 1, b => 2, c => 11}, {a => 3, c => 12}, {a => 5, b => 6} ];

    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

      I think you are right, in such circumstance I think I would use an index:

      Something like:

      for my $i (0..$#{$data}) { foreach ( keys %{$data->[$i]} ) { $columns->{$_}->[$i] = $data->[$i]->{$_} ; } ; }

      Also makes it fairly easy to see what happens:

      $columns->{$_}->[$i] = $data->[$i]->{$_} ; hash------^-------------------------^ array-----------^-------------^
      The disadvantage here is, that you might loose null-values due to missing keys in your data

      ... which you didn't mention at all in the root node. Changing the specs on us is not nice :-P Is this example you've shown now representative, or are there other edge cases?

        ... which you didn't mention at all in the root node

        You are right. This is because it was obvious to me. I think this happens to every programmer.

        Sorry.

        or are there other edge cases

        None that I know of.


        s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
        +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e