How can I find all matches to a regular expression in Perl?

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

#!/usr/bin/perl

use strict; use warnings;

my $str = <<EO_STR;
Name=Value1
Name=Value2
Name=Value3
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.


my @values;
while(<DATA>){
  chomp;
  push @values, /Name=(.+?)$/;
}   
print join " " => @values,"\n";

__DATA__
Name=Value1
Name=Value2
Name=Value3

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

push (@matches,$&) while($string =~ /=(.+)$/g );

Tags:

Regex

Perl