Hacking Google Maps and Google Earth (ExtremeTech)

(Dana P.) #1

Chapter 5 — Storing and Sharing Information 69


chomp;
$csv->parse($_);
my ($id,$ref,$fname,$lname,$country) = $csv->fields;
print “ID: $id\nRef: $ref\nFirst: $fname\nLast: $lname\nCountry:
$country\n”;
}


close(DATA);


Writing Delimited Files.


Writing delimited files is also easy. You only have to separate each field of data with the delim-
iting character and each record with a carriage return. In Perl, doing is this is as easy as com-
bining a printstatement with jointo merge fields together with your delimiter. You can see
a sample of writing to a tab-delimited file (TDF) in Listing 5-3.


Listing 5-3:Writing to a Tab-Delimited File

print(join(“\t”,145,1385674,’Martin’,’Brown’,’United Kingdom’),”\n”);


When you are writing a CSV file, you should also quote each field of data in double quotes.
Even though you may not need to quote the data in this way (it is only a requirement for fields
that contain a comma), it won’t do any harm if you do it anyway. Listing 5-4 shows an example
of writing to a CSV file, again in Perl. In this example, I run a list of values through the map
function to quote them, and then use jointo merge the fields, separated by commas, together
into the record.


Listing 5-4:Writing to a Comma-Separated Value File

use Text::CSV_XS;


open(DATA,$ARGV[0]) or die “Couldn’t open file: $!”;


my $csv = Text::CSV_XS->new();


while()
{
chomp;
$csv->parse($_);
my ($id,$ref,$fname,$lname,$country) = $csv->fields;
Continued

Free download pdf