Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: perl print to csv

by Athanasius (Archbishop)
on Apr 21, 2015 at 03:58 UTC ( [id://1124102]=note: print w/replies, xml ) Need Help??


in reply to perl print to csv

Hello bishop2001,

First, please enclose code and data in <code> ... </code> tags; see Markup in the Monastery.

Second, to get the output you want, you need to work backwards and design an appropriate data structure. In this case, I think you would be better off with a hash keyed to times, with each value an inner hash of name/value pairs:

{ "1427766555" => { bob => 10 }, "1427766556" => { bill => 5 }, "1427766557" => { bob => 12 }, }

(I am assuming that, in a data entry of the form 12,1427766557, bob, the first field is the “value” and the second is the time.)

Once you have this data structure, you can write the code:

#! perl use strict; use warnings; my (%names, %times); while (<DATA>) { chomp; my ($value, $time, $name) = split /,\s*/; next unless defined $name; $names{$name} = undef; $times{$time}->{$name} = $value; } print join(',', 'time', sort keys %names), "\n"; for my $time (sort keys %times) { print $time, ','; for my $name (sort keys %names) { print +(exists $times{$time}->{$name}) ? $times{$time}->{$name} : '', ','; } print "\n"; } __DATA__ 12,1427766557, bob 5,1427766556, bill 10,1427766555, bob

Output:

13:55 >perl 1224_SoPW.pl time,bill,bob 1427766555,,10, 1427766556,5,, 1427766557,,12, 13:55 >

Third (and notwithstanding the above code), when dealing with CSV files, you are generally well-advised to use a dedicated module, such as Text::CSV_XS.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2024-04-25 09:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found