Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am very new to Perl (like less than 72 hours) and I have what I believe is a simple question but, I just can't find the information to implement my solution.

I have a comma seperated file with up to hundreds of records where I need to modify the data depending on a value of a particular field. Below is an example or one record in a file.


20020604,Billable,John Smith,Regular,1, Project A


What I want to know is how do I read and print out one value from the record like if I just wanted the string "Regular". Thanks.
  • Comment on Reading individual variables from a file.

Replies are listed 'Best First'.
Re: Reading individual variables from a file.
by mirod (Canon) on Jun 17, 2002 at 21:44 UTC

    After 72 hours of Perl I think it is time for you to learn about CPAN, the Comprehensive Perl Archive Network.

    Start by reading A Guide to Installing Modules.

    In your case you can try Text::CSV_XS, which processes Comma Separated Values, exactly the format you are using.

    You can then have a look at Module Reviews for a (non exhaustive) list of modules, and use search.cpan.org for even more module galore.

Re: Reading individual variables from a file.
by thunders (Priest) on Jun 17, 2002 at 21:48 UTC
    If you're totally new to programming you may not appreciate this but with DBI and DBD::CSV you get the ability to run SQL statements on comma separated files like that. It's great for large or interrelated CSV dumps
    more simply you want open the file to move through the file line by line and split on a comma. see open perlfaq5 and while (and close). to get the fifth item something like this is a good way  $fifth_item = (split(/,/,$line))[4];
Re: Reading individual variables from a file
by cjf (Parson) on Jun 17, 2002 at 22:14 UTC
      Thank you very much for you help everyone. I'm going back to check all of your suggestions now.
        Back again. So my next question is how do I print the 3rd in that example.
        Is split or CVS_XS still the best option to do that?
Re: Reading individual variables from a file.
by DamnDirtyApe (Curate) on Jun 17, 2002 at 21:29 UTC
      Using split will fail if any of the input contains a comma. It's more likely than people think. Over the years I've run into many problems with customers and vendors who have bad product data feeds because they used a simple split and call is CSV.

      I'd highly recommend Text::CSV_XS

      -Lee

      "To be civilized is to deny one's nature."
      A reply falls below the community's threshold of quality. You may see it by logging in.