My first go at dealing with delimited data has not been as straightforward as I expected :(

After stuffing around with various Text/CSV modules and super searching all over the place for an hour or two, I finally gave up and decided to write my own parsing routine.

The data is tab delimited, with the first line being a header.
Each column represents user attributes, and each row represents the data for a particular user.
The only inconsistency in the data (if it is that), is that the header row has a leading hash (#), whereas the rest of the data doesn't.

All I wanted to do is build a hash from the data, in the form $data->{$user}{$attribute}

Although the code I have works, and is only about a dozen lines, I'm disappointed - because:

a) I'm sure this could be done easier with the appropriate module - but I'm damned if I could work out how, and
b) I've used both a flag and a counter, which I'm sure are redundant - but I don't know how to get rid of them

Any advice?
Thanks in advance
--Darren
#!/usr/bin/perl -w use strict; my $datafile = "stuff.csv"; my @fields; my $data; my $flag; open DATA, "<$datafile" or die "Could not open $datafile:$!\n"; while (<DATA>) { chomp(); # If the flag hasn't been set, this must be the header (first) lin +e if (!$flag) { # Throw away the first two fields (#, username) in the header (undef, undef, @fields) = (split /\t/); $flag++; } else { my ($user, @userdata) = (split /\t/); my $i = 0; while ($i <= $#fields) { $data->{$user}{$fields[$i]} = $userdata[$i]; $i++; } } } close DATA;

In reply to Parsing CSV into a hash by McDarren

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.