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

Greetings Monks, I have a csv file which I'll use Perl to read in and do some manipulations and then output it in a new .csv file. Snippet of the input file (not the first 3 lines of the file). Each line starts with the word "map":
Map,Axxxx,F,Bxxxx,BXXXX Axxxx,000000,000000,XXX-XXXXXXXX-XX,,NOTE:XXXX +X Xxxxx (000000)@EX%SMTP:xxxxx.xxxxx@xx.com%X400:c=CA;a= ;p=XX;o=xxxx +xxxxxxxxx;s=XXXXX;g=Xxxxx;,p:000000@mail,Customer Srv Centre,WORKS/ S +RV,SUPPORT/ SUPPORT,AXD3, + 0000,(000) 000-0000,(000) 000-000,,,666 S +nowball Paves,Vancouver,ON,CAN,J7G 3Y4,/o=O:ou=AR3/000000, Map,...
Here is the code that I used. I am using Perl 5.8 on a Unix machine.
#!/usr/local/bin/perl use strict; use Text::CSV_XS; my ($mday, $mon, $year) = (localtime(time))[3..5]; my $cdate = sprintf "%02d" x 3, $mon+1, $mday, $year%100; my $infile = "inmap.csv"; my $outfile = "outmap${cdate}.csv"; open( INFILE, $infile); open (OUTFILE, ">", $outfile); my $csv = Text::CSV_XS->new({binary=>1}); while (defined(my $line = <INFILE>)) { next if $. == 1; chomp $line; if (my $status = $csv->parse($line)) { my @columns = $csv->fields; # quote columns with commas @columns = quotecolumn(@columns); #get email address for (9) { $columns[$_] =~ s/^.*SMTP://; $columns[$_] =~ s/\%.*$//; $columns[$_] =~ s/\".*$//; } #get street number and name for (20) { $columns[$_] =~ s/,.*$//; } print OUTFILE join(",", @columns[1,2,3,4,5,9,11,12,13,15,16,17,18, +19,20,21,22,23,24]), "\n"; } } close (INFILE); close (OUTFILE); sub quotecolumn { my @columns = @_; for (@columns) { if (/,/) { unless (/^"[^"]*"$/) { $_ = qq("$_"); } } } return @columns; }
Everything works except the getting the street number and name part. For example: for the first line, I would like the Address column to only contain 666 Snowball Paves and not 666 Snowball Paves,Vancouver,ON,CAN,J7G 3Y4. When I run the above code, it doesn't give me only the street number and name, it gives me everything. I'm a beginner in Perl and any help would be appreciated. Thanks in advance!

20050511 Edited by Corion: Wiped personal information from the post

Replies are listed 'Best First'.
Re: parsing a field
by eibwen (Friar) on May 11, 2005 at 14:21 UTC

    Nevertheless, the problem remains that the OP was using the incorrect column specification.

    UPDATE: Changed the for loop from the OP's implementation to actually maintain the quoted values.