Reputation:
I have an array of hashes (AoH) which looks like this:
$VAR1 = [
{
'Unit' => 'M',
'Size' => '321',
'User' => 'test'
}
{
'Unit' => 'M'
'Size' => '0.24'
'User' => 'test1'
}
...
];
How do I write my AoH to a CSV file with separators, to get the following result:
test;321M
test1;0.24M
I've already tried this code:
my $csv = Text::CSV->new ( { sep_char => ';' } );
$csv->print( $fh1, \@homefoldersize );
But I get
HASH(0x....)
in my CSV file.
Upvotes: 0
Views: 591
Reputation: 126722
All that is necessary is
printf "%s;%s%s\n", @{$_}{qw/ User Size Unit /} for @homefoldersize;
Upvotes: 1
Reputation: 53478
Pretty fundamentally - CSV
is an array based data structure - it's a vaguely enhanced version of join
. But the thing you need for this job is print_hr
from Text::CSV
.
First you need to set your header order:
$csv->column_names (@names); # Set column names for getline_hr ()
Then you can use
$csv -> print_hr ( *STDOUT, $hashref );
E.g.
$csv -> column_names ( qw ( User Size Unit ) );
foreach my $hashref ( @homefoldersize ) {
$csv -> print_hr ( *STDOUT, $hashref );
}
As you want to concatenate a couple of your columns though, that's slightly harder - you'll need to transform the data first, because otherwise Size
and Unit
are separate columns.
foreach my $hashref ( @homefoldersize ) {
$hashref -> {Size} .= $hashref -> {Unit};
delete $hashref -> {Unit};
}
Additionally -as another poster notes - you'll need to set sep_char
to change the delimiter to ;
.
As an alternative to that - you could probably use a hash slice:
@values = @hash{@keys};
But print_hr
does pretty much the same thing.
Upvotes: 1
Reputation: 5948
Try using the example for Text::CSV posted here: http://search.cpan.org/~makamaka/Text-CSV-1.33/lib/Text/CSV.pm
You will need to set sep_char = ';'
to make it semicolon-separated.
Upvotes: 0