Juan
Juan

Reputation: 33

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 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 !!

Upvotes: 2

Views: 1600

Answers (5)

Sinan Ünür
Sinan Ünür

Reputation: 118118

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.

Upvotes: 5

Brad Gilbert
Brad Gilbert

Reputation: 34120

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;

Upvotes: 2

Juan
Juan

Reputation: 33

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?

Upvotes: 1

jamessan
jamessan

Reputation: 42647

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.

Upvotes: 7

Paul Nathan
Paul Nathan

Reputation: 40299

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.

Upvotes: 2

Related Questions