Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Padding with zeroes fails

by Kickstart (Pilgrim)
on Dec 06, 2001 at 00:22 UTC ( #129733=perlquestion: print w/replies, xml ) Need Help??

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

Can anyone tell me why this doesn't work? I'm a bit lost.

use strict; use diagnostics; # ScheduleA has the format of: # ,,,,,,,MultiPlex MP-7 Plan.pdf.sit # ,,,,,,,MultiPlex S2.1 Main Plan.S.sit. . . # ,,,,,,,MultiPlex S2.2 Upper PlanS.sit. . . # ,,,,,,,MultiPlex S2.3 Roof Plan.S.sit. . . # 1/24/2000,906,907,Johnston Sport Architecture Inc.,Lorne Mack # 1/21/2000,908,908,Johnston Sport Architecture Inc.,Lorne Mack # 1/19/2000,909,911,Johnston Sport Architecture Inc.,Lorne Mack # ,,,,,,,Whitehorse FTP Memo.pdf # ,,,,,,,1122 Whitehorse FTP 6.0/95 open (CSVFILE, "<schedulea.csv") or die "Can't open schedulea.csv"; while (<CSVFILE>) { if ($_ =~ /(^.*?),(\d+),(\d+),(.*?$)/) { $2 =~ ('0' x (6 - length($2))) . $2; $3 =~ ('0' x (6 - length($3))) . $3; print "$1,$2,$3,$4\n"; } else { print $_; } }



Replies are listed 'Best First'.
(Ovid) Re: Padding with zeroes fails
by Ovid (Cardinal) on Dec 06, 2001 at 00:35 UTC

    You really shouldn't try to parse CSV data by hand. Having a quoted field with an embedded comma will quickly make your life miserable. If you create a regex which will accurately parse CSV data, then it's going to be less than pleasant to maintain. Try something like Text::CSV_XS:

    use strict; use Text::CSV_XS; my $csv = Text::CSV->new; my $csv_file = 'schedulea.csv'; open CSVFILE, "< $csv_file" or die "Can't open $csv_file for reading: +$!"; while (<CSVFILE>) { my $status = $csv->parse($_); if ( $status ) { my @columns = $csv->fields(); # do stuff with columns } else { my $bad_argument = $csv->error_input(); # do stuff with the error } }


    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: Padding with zeroes fails
by miyagawa (Chaplain) on Dec 06, 2001 at 00:25 UTC
      Thanks, that was definitely the first error...the second came up when I attempted to assign other values to the read-only variables ($2 and $3)...both fixed, worked like a charm. Unfortunately this is just a one-of, so I didn't want to write a big multi-use script. Kickstart

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://129733]
Approved by root
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2023-12-09 15:50 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (38 votes). Check out past polls.