Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Hi,

I just read this thread again and saw your reply.

Assuming, that an empty string is not a valid value, I came up with this:

#! /usr/bin/perl use strict; use warnings; use Text::CSV_XS; my $csv = Text::CSV_XS->new({ binary => 1, allow_whitespace => 1, }) or die "Cannot use CSV: " . Text::CSV_XS->error_diag(); # for testing; in real world, open file and use that handle my $fh = \*DATA; my (%hash, @hdr); while ( my $row = $csv->getline( $fh ) ) { # header not yet defined? or 1st cell starts with '<' ==> use row +as header if ( !@hdr || $row->[0] =~ m/^</ ) { @hdr = @{$row}; next; } # otherwise try to process data else { for my $i ( 0 .. $#hdr ) { # only add those values which contain at least one charact +er # so: no "undef"s or empty strings in result # if empty strings are OK or wanted, try to replace length +() with defined() push @{ $hash{$hdr[$i]} }, ( length $row->[$i] ? $row->[$i +] : () ); } } } # check created data structure require Data::Dumper; $Data::Dumper::Sortkeys = 1; print Data::Dumper::Dumper( \%hash ); __DATA__ <A1>, <A2>, <A3> a1, aa1, aaa1 a2, , aaa2 a3, aa3 a4 <B1>, <B2> b1, bb1 b2, bb2 b3
That produced a result like this:
$VAR1 = { '<A1>' => [ 'a1', 'a2', 'a3', 'a4' ], '<A2>' => [ 'aa1', 'aa3' ], '<A3>' => [ 'aaa1', 'aaa2' ], '<B1>' => [ 'b1', 'b2', 'b3' ], '<B2>' => [ 'bb1', 'bb2' ] };

In reply to Re^4: Help parsing a complicated csv by linuxer
in thread Help parsing a complicated csv by rmfin730

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-04-23 07:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found