Dmytro Leonenko
Dmytro Leonenko

Reputation: 1501

How do I extract words from a comma-delimited string in Perl?

I have a line:

$myline = 'ca,cb,cc,cd,ce';

I need to match ca into $1, cb into $2, etc..

Unfortunately

$myline =~ /(?:(\w+),?)+/;

doesn't work. With pcretest it only matches 'ce' into $1. How to do it right?
Do I need to put it into the while loop?

Upvotes: 2

Views: 11156

Answers (5)

Courtland
Courtland

Reputation: 56

Look into the CSV PM's you can download from CPAN, i.e. Text::CSV or Text::CSV_XS.

This will get you what you need and also account for any comma seperated values that happen to be quoted.

Using these modules make it easy to split the data out and parse through it...

For example:

my @field = $csv->fields;

Upvotes: 3

FMc
FMc

Reputation: 42411

Although split is a good way to solve your problem, a capturing regex in list context also works well. It's useful to know about both approaches.

my $line = 'ca,cb,cc,cd,ce';
my @words = $line =~ /(\w+)/g;

Upvotes: 3

Quick Joe Smith
Quick Joe Smith

Reputation: 8222

If the number of elements is variable, then you're not going to do it in the way you're aiming for. Loop through the string using the global flag:

while($myline =~ /(\w+)\b/g) {
    # do something with $1
}

I am going to guess that your real data is more complex than 'ca,cb,cc,cd,ce', however if it isn't then the use of regular expressions probably isn't warranted. You'd be better off splitting the string on the delimiting character:

my @things = split ',', $myline;

Upvotes: 1

David Webb
David Webb

Reputation: 193686

Why not use the split function:

@parts = split(/,/,$myline);

split splits a string into a list of strings using the regular expression you supply as a separator.

Upvotes: 10

Dana
Dana

Reputation: 2739

Isn't it easier to use my @parts = split(/,/, $myline) ?

Upvotes: 9

Related Questions