views:

225

answers:

4

I am attempting to parse a string in Perl with the format:

Messages pushed to the Order Book queues 123691 121574 146343 103046 161253

I want to access the numbers at the end of the string so intend to do a match like

/(\d+)/s

My issue is that the number of values at the end contain a variable number of strings.

What is the best way to format the regexp to be able to access each of those numbers individually? I'm a C++ developer and am just learning Perl, so am trying to find the cleanest Perl way to accomplish this.

Thanks for your help.

A: 

I'd do something like this:

my @numbers;
if (m/Messages pushed to the Order Book queues ([\d\s]+)/) {
   @numbers = split(/\s+/, $1);
}

No need to cram it into one regex.

bmdhacks
There are many more elegant ways of doing this, see the other answers.
Chas. Owens
+1  A: 

"In scalar context, each execution of m//g finds the next match, returning true if it matches, and false if there is no further match" --(From perldoc perlop)

So you should be able to make a global regex loop, like so:

while ($string =~ /(\d+)/g) {
    push @queuelist, $1;
}
Plutor
That's a bit more work than you really need. :)
brian d foy
+7  A: 

Just use the /g flag to make the match operator perform a global match. In list context, the match operator returns all of the results as a list:

@result = $string =~ /(\d+)/g;

This works if there are no other numbers than the trailing ones.

fgm
+4  A: 

You can use the match operator in a list context with the global flag to get a list of all your parenthetical captures. Example:

@list = ($string =~ /(\d+)/g);

Your list should now have the all the digit groups in your string. See the documentation on the match operator for more info.

A. Levy