我想编写一个名为“逗号”的perl函数(sub),它将一个字符串作为输入,将字符串拆分为一个数组

时间:2015-02-11 07:52:33

标签: perl

我想编写一个名为"逗号"的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;

1 个答案:

答案 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