The nice thing about Perl is that it very often does what you want without you having to jump through hoops. If you supply a file name (or multiple file names) as an argument, Perl will automatically open the file for you so you can read it using an empty <> (readline) function. The following steps create a simple CSV file and an equally simple script to read it.
$ cat > xxx.csv
Fred,male,25
Beth,female,31
Joe,male,22
$ cat > xxx
#!/usr/bin/perl
#
use strict;
use warnings;
while ( <> ) # Read the file supplied as argument
{
chomp; # Remove line terminator
my( $name, $sex, $age ) = split m{,};
printf qq{Name: %s\n Sex: %s\n Age: %s\n-----\n},
$name, $sex, $age;
}
$ chmod +x xxx
$ ./xxx xxx.csv
Name: Fred
Sex: male
Age: 25
-----
Name: Beth
Sex: female
Age: 31
-----
Name: Joe
Sex: male
Age: 22
-----
$
I hope this is helpful.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|