Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Comment on

( #3333=superdoc: print w/ replies, xml ) Need Help??

Alright, here we go. For these examples I assume you have a file some_csv.csv, with the following contents:

Name,Type,Age Lily,Cat,4 Buster,Dog,5 Tweety,Bird,2

The first approach is the 'naive' one. It does exactly what you want as specified, but it looks a bit messy.

use strict; use warnings; use Text::CSV; use subs qw(hlookup); print "The animal in line 2 is ", hlookup("some_csv.csv", "Age", 2), " + years old.\n"; print "The critter in line 4 is called ", hlookup("some_csv.csv", "Nam +e", 4), ".\n"; sub hlookup { my $csv_file = shift; my $field_name = shift; my $row_num = shift; my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary + attribute. or die "Cannot use CSV: ".Text::CSV->error_diag (); open my $fh, "<:encoding(utf8)", $csv_file or die "test.csv: $!"; my $field_num; my $first_row = $csv->getline( $fh ); my @result; for (my $idx = 0; $idx <= @$first_row; $idx++) { if ($first_row->[$idx] eq $field_name) { $field_num = $idx; push @result, $first_row->[$field_num]; last; } } die "Field name '$field_name' not found on the first row of $csv_ +file" if not defined $field_num; while ( my $row = $csv->getline( $fh )) { push @result, $row->[$field_num]; } $csv->eof or $csv->error_diag(); close $fh; return $result[$row_num - 1]; # -1 since array indexes are 0-bas +ed, # and we count our lines 1-based }

The second approach used Text::CSV's ability to give fields names. What I did here was read the first row, tell Text::CSV that the values of the fields are actually the names for that field, and then I told Text::CSV to get me the field of the row I'm interested in. It's a little bit clearer, and most of the looping is delegated to Text::CSV. I like it when my modules do my heavy lifting for me.

use strict; use warnings; use Text::CSV; use subs qw(hlookup); print "The animal in line 2 is ", hlookup("some_csv.csv", "Age", 2), " + years old.\n"; print "The critter in line 4 is called ", hlookup("some_csv.csv", "Nam +e", 4), ".\n"; sub hlookup { my $csv_file = shift; my $field_name = shift; my $row_num = shift; my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary + attribute. or die "Cannot use CSV: ".Text::CSV->error_diag (); open my $fh, "<:encoding(utf8)", $csv_file or die "test.csv: $!"; my $field_num; my $first_row = $csv->getline( $fh ); $csv->column_names(@$first_row); my $all = $csv->getline_hr_all($fh, $row_num - 2, 1); # - 2 since array indexes are 0-based, # and we count our lines 1-based, # and because we've already read the first # line. return $all->[0]->{$field_name} }

Both examples give me the output I will list below. I've also tried dabbling with DBD::CSV, because I thought it'd be nice if we could extract our information with SQL! But that's a module that allows you to set up entire relational database in CSV files, which is pretty much overkill for what we're trying to do here.

Anyway, I'm sure these aren't the only approaches to go at things, but it surely should get you going. And you owe me nothing, it was my pleasure. But if you insist, I can send you my paypal account through a private message ;)

The animal in line 2 is 4 years old. The critter in line 4 is called Tweety.

In reply to Re^7: Parse .csv file from FTP using Perl by muba
in thread Parse .csv file from FTP using Perl by Sherlock Perl

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!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.
  • Log In?
    Username:
    Password:

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

    How do I use this? | Other CB clients
    Other Users?
    Others lurking in the Monastery: (5)
    As of 2014-10-20 05:42 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      For retirement, I am banking on:










      Results (72 votes), past polls