joe
joe

Reputation: 35077

How can I extract fields from a CSV file in Perl?

I want to extract a particular fields from a csv file (830k records) and store into hash. Is there any fast and easy way to do in Perl with out using any external methods?

How can I achieve that?

Upvotes: 5

Views: 1009

Answers (4)

taiko
taiko

Reputation: 448

using split command would do the job I guess. (guessing columns are separated by commas and no commas present in fields)

    while (my $line = <INPUTFILE>){
    @columns= split ('<field_separator>',$line);  #field separator is ","
    }

and then from elements of the "column" array you can construct whatever hash you like.

Upvotes: -1

brian d foy
brian d foy

Reputation: 132775

Use Text::CSV_XS. It's fast, moderately flexible, and extremely well-tested. The answer to many of these questions is something on CPAN. Why spend the time to make something not as good as what a lot of people have already perfected and tested?

If you don't want to use external modules, which is a silly objection, look at the code in Text::CSV_XS and do that. I'm constantly surprised that people think that even though they think they can't use a module they won't use a known and tested solution as example code for the same task.

Upvotes: 11

p.marino
p.marino

Reputation: 6252

See also this code fragment taken from The Perl Cookbook which is a great book in itself for Perl solutions to common problems

Upvotes: -1

ghostdog74
ghostdog74

Reputation: 342313

assuming normal csv (ie, no embedded commas), to get 2nd field for example

 $ perl -F"," -lane 'print $F[1];' file

Upvotes: -1

Related Questions