develooper Front page | perl.beginners | Postings from August 2009

Re: Regular expression help

Thread Previous | Thread Next
From:
Chas. Owens
Date:
August 25, 2009 23:42
Subject:
Re: Regular expression help
Message ID:
58ce48dc0908252341n72b74f5bs2a5a3925af3aa9eb@mail.gmail.com
On Wed, Aug 26, 2009 at 02:23, Dave Tang<d.tang@imb.uq.edu.au> wrote:
> Dear list,
>
> I am trying to import entries in a csv file into a relational database,
> however there are entries such as:
>
> a,b,c,d,e,"f1,f2","g1,g2" which spoil my split(/,/).
snip

Sounds like a job for [Text::CSV][1].  Of course, you an always write
a quick parser:

#!/usr/bin/perl

use strict;
use warnings;

my $line = q/a,b,c,d,e,"f1,f2","g1,g2"/;

my $in_string;
my @rec = ("");
for my $token ($line =~ /([,"]|[^,"]+)/g) {
	if ($in_string) {
		if ($token eq q/"/) {
			$in_string = 0;
			push @rec, "";
			next;
		}
	} elsif ($token eq q/,/) {
		push @rec, "";
		next;
	} elsif ($token eq q/"/) {
		$in_string = 1;
		next;
	}
	$rec[-1] .= $token;
}

print join("|", @rec), "\n";


[1] : http://search.cpan.org/dist/Text-CSV/lib/Text/CSV.pm

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About