开发者

In Perl, how can I get the fields in this CSV string into an array without spaces?

if I have a string, say:

my $string = "A, B,C, D , E ";

How can I put this into an array in Perl without the leading and trailing spaces? So what I want is only a single letter in each array element. What I currently do is开发者_C百科 this:

my @groups = split /,\s*/, $string;

But this is obviously not enough, as the trailing spaces are still there. Any help appreciated. Thanks a lot !!


Then strip leading/trailing spaces before you split and match the leading/trailing spaces in the split expression.

my $string = " A, B,C, D , E ";
$string =~ s/^\s+//;
$string =~ s/\s+$//;
my @groups = split /\s*,\s*/, $string;

Using a module like Text::CSV is probably better than trying to do your own CSV parsing, though.


my @groups = map { s!^\s+!!; s!\s+$!!; $_ } split /,/, $string;

or

my @groups = $string =~ /([A-Z])/g;

However, unless the input is really as simple as you have shown, you would be better off using Text::CSV or Text::xSV.


Here you go:

@groups = split /,/, $string;
#remove whitespace now.
@groups = map { s/^\s+//; s/\s+$//; $_ } @groups;

Note: the regex can be simplified I'm pretty sure, just haven't worked it out yet.


You don't have to limit yourself to split, you just use a match with the /g modifier.

my $string = " A, B,C, D , E ";
my @groups = $string =~ /\s*([^,]+?)\s*,?/g;


Just to make sure I'm not missing something, after trying to demystify your examples, I came up with this:

my $string = " A, B,C, D , E ";
$string =~ s/\s+//g;
my @groups = split /,/, $string;

Would work either I guess?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜