我想编写一个名为"逗号"的perl函数(sub)。这需要一个字符串 输入,将字符串拆分为基于逗号的数组(忽略 逗号周围的空格,并返回一个字符串数组。该 catch是任何元素都可以包含在引号中,其中包含逗号 将被允许。
hello,"world, yo",matt
hello
"world, yo"
math
one,two,"three,three and a half", four ,"five, five and a half",six
one
two
"three,three and a half"
four
"five, five and a half"
six
my $testb = "hello,'world, yo',matt";
print $_, "\n" for split ',', $testb;
my $testc = "one,two,"three,three and a half", four ,"five, five and a half",six";
print $_, "\n" for split ',', $testc;
答案 0 :(得分:2)
Text :: CSV是个更好的主意!无论如何我喜欢写Perl ......
#!/usr/bin/perl
sub comma{ my $s=shift; ## poor man's CSV
my %save=();
my $i=0;
$s =~ s/(".*?")/$save{++$i}=$1; "--$i--"/ge; ## save strings
map {s/--(\d+)--/$save{$1}/r} split(/\s*,\s*/,$s); ## split and restore
}
while(<DATA>){ ## testing
print join("\n---",comma($_)),"\n";
}
__DATA__
one,two,"three,three and a half", four ,"five, five and a half",six