APM: Regular Expression Question

Wayne Walker wwalker at bybent.com
Wed Aug 16 14:53:07 PDT 2006


# split/join solution:
foreach my $piece (@pieces) {
	# split into separate columns
	my @columns = split(/\t/, $piece);
	# pop off last column since we don't want to quote it
	my $last_column = pop @columns;
	# use qq with "'s as it's easier to read, IMO
	# use map to quote the columns
	# tack on the last column and it's associated whitespace
	print join("\t", map { qq("$_") } @columns), "\t$last_column\n";
}

# format solution - exercise for the student, but I think perl's format
# statement would make this something like:
format FORMATNAME = "^*"\t"^*"\t"^*"\t"^*"\t"^*"\t"^*"\t^*
foreach my $piece (@pieces) {
	# split into separate columns
	my @columns = split(/\t/, $piece);
	print FORMATNAME, @columns;
}
# I've not used FORMAT in more than a decade!

# one regex solution
# use $_ for brevity/clarity
foreach (@pieces) {
	s/^/"/; # add a leading "
	s/\t/"\t"/g;
	s/"(\S+)/\1/; # Replace the last quote and that which follows it, with
				# just what follows it
	print;
}

The split/join is probably fastest.  I did not test any of the above
code.

-- 

Wayne Walker

www.unwiredbuyer.com - when you just can't be by the computer

wwalker at bybent.com                    Do you use Linux?!
http://www.bybent.com                 Get Counted!  http://counter.li.org/
Perl - http://www.perl.org/           Perl User Groups - http://www.pm.org/
Jabber:  wwalker at jabber.gnumber.com   AIM:     lwwalkerbybent
IRC:     wwalker on freenode.net


More information about the Austin mailing list