Take the 2-minute tour ×

I have text in the form:


Using Perl, I would like to match /Name=(.+?)/ every time it appears and extract the (.+?) and push it onto an array. I know I can use $1 to get the text I need and I can use =~ to perform the regex matching, but I don't know how to get all matches.

share|improve this question
Related: stackoverflow.com/questions/1034027/… –  Sinan Ünür Nov 12 '09 at 16:30

5 Answers 5

up vote 30 down vote accepted

A m//g in list context returns all the captured matches.


use strict; use warnings;

my $str = <<EO_STR;

my @matches = $str =~ /=(\w+)/g;
# or my @matches = $str =~ /=([^\n]+)/g;
# or my @matches = $str =~ /=(.+)$/mg;
# depending on what you want to capture

print "@matches\n";

However, it looks like you are parsing an INI style configuration file. In that case, I will recommend Config::Std.

share|improve this answer
The important thing to note is the g at the end of the regular expression. –  mob Nov 12 '09 at 16:22
Actually, I simplified the format. There's text in the middle, but until I handled the simple case, there was no hope of me handling the larger case. –  Thomas Owens Nov 12 '09 at 16:33
my @values;
  push @values, /Name=(.+?)$/;
print join " " => @values,"\n";

share|improve this answer
Don't use $1 if the regex didn't succeed: /Name=(.+?)$/ and push @values, $1. Or even just my @values = map /Name=(.+?)$/, <DATA>; –  ysth Nov 12 '09 at 19:17

The following will give all the matches to the regex in an array.

push (@matches,$&) while($string =~ /=(.+)$/g );
share|improve this answer

Use a Config:: module to read configuration data. For something simple like that, I might reach for ConfigReader::Simple. It's nice to stay out of the weeds whenever you can.

share|improve this answer

Instead of using a regular expression you might prefer trying a grammar engine like:

I've given a snippet of a Parse::ResDescent answer before on SO. However Regexp::Grammars looks very interesting and is influenced by Perl6 rules & grammars.

So I thought I'd have a crack at Regexp::Grammars ;-)

use strict;
use warnings;
use 5.010;

my $text = q{
Name = Value2

my $grammar = do {
    use Regexp::Grammars;

        <rule: VariableDeclare>
            <Var> \= <Value>

        <token: Var>    Name

        <rule: Value>   <MATCH= ([\w]+) >

if ( $text =~ $grammar ) {
    my @Name_values = map { $_->{Value} } @{ $/{VariableDeclare} };
    say "@Name_values";

The above code outputs Value1 Value2 Value3.

Very nice! The only caveat is that it requires Perl 5.10 and that it may be overkill for the example you provided ;-)


share|improve this answer

Your Answer


