I’ve been banging my head on the wall for several hours.
I have a data structure that looks like this (output from "Data :: Dumper"). This is my own mistake, I am creating a data structure as I am parsing some data.
print Dumper $data;
___OUTPUT___
$VAR = { 'NAME' => {
'id' => '1234',
'total' => 192,
'results' => {
'APPLE' => 48 ,
'KUMQUAT' => 61 ,
'ORANGE' => 33 ,
}
}
}
- There are thousands of "NAME" keys.
- There is only one id and total.
- A "hash" of results can have one or more key / value pairs.
I want to print a comma separated list, first sorted by "total", and then by the value of each hash in the "results" array.
The following code was used to print the CSV from an already saved data structure.
use strict;
use warnings;
open (my $fh, >out.csv);
print $fh "Name, ID, Label, Count, Total\n";
foreach ( sort { $data->{$b}->{total} <=> $data->{$a}->{total} }
keys %{$data} )
{
my $name = $_;
foreach (
sort {
$data->{$name}->{results}->{$a} <=> $data->{$name}->{results}
->{$b}
} values %{ $data->{$name}->{results} }
)
{
print $fh $name . ","
. $data->{$name}->{id} . "," . "'"
. $_ . ","
. $data->{$name}->{results}->{$_} . "," . "\n";
}
print $fh $name . ","
. $data->{$name}->{id} . "," . "," . ","
. $data->{$name}->{total} . "\n";
}
close($fh);
( , Perl).
:
Name, ID, Label, Count, Total
foo, 1234, ORANGE, 33,
foo, 1234, APPLE, 48,
foo, 1234, KUMQUAT, 61,
foo, 1234, , , 142
bar, 1101, BIKE, 20,
bar 1101, , , 20
! , ( "" ), , "" ...
print Dumper $data;
___OUTPUT___
$VAR = { 'NAME' => {
'id' => '1234',
'total' => 192,
'results' => [
{ 'APPLE' => 48 },
{ 'KUMQUAT' => 61 },
{ 'ORANGE' => 33 },
{ 'APPLE' => 50 },
]
}
}
- "NAME".
- "id" "total" .
- "results" .
- "results" /.
, , , , ...; -)
sort/print.
use strict;
use warnings;
open (my $fh, >out.csv);
print $fh "Name, ID, Label, Count, Total\n";
foreach ( sort { $data->{$b}->{total} <=> $data->{$a}->{total} }
keys %{$data} )
{
my $name = $_;
foreach (
sort {
$data->{$name}->{results}->{$a} <=> $data->{$name}->{results}
->{$b}
} values %{ $data->{$name}->{results} }
)
{
}
print $fh $name . ","
. $data->{$name}->{id} . "," . "," . ","
. $data->{$name}->{total} . "\n";
}
close($fh);
, .
, .
- , , , ! ( , ... "" , . ( Perl) .)