English 中文(简体)
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?

最佳回答

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.

问题回答

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

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;

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;

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+)/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;




相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签