I was wondering if there is a global matching flag, considering there is a global replacement flag (/g)

I'm using this workaround to make multiple matches in a string

while(!$stop_var)
     {
         if($source =~ /(PATTERN)/i)
         {
             push(@matches, $1);
             $source = $';
         }
         else
         {
             $stop_var =1;
         }
         
     }

is there an easier way?

Recommended Answers

All 4 Replies

push @matches, $1 while ($source=~ m{(PATTERN)}g);

Is this you want ?

Thanks k_manimuthu worked perfectly!

push @matches, $1 while ($source=~ m{(PATTERN)}g);

Is this you want ?

That looks good. Alternatively, you can assign the result of a global match to an array directly, without a loop.

#!/usr/bin/perl
use strict;
use warnings;

my $source = '1 door and only 1 and yet its sides are 2';
my $pattern = qr/\ba\w*\b/;

my @matches = $source =~ m/$pattern/g;

print "Matches are:\n", join "\n", @matches;

#Matches are:
#and
#and
#are
use strict;
use warnings;

my $pattern="1234";

undef($/);
my @array;
my $count;
while(<DATA>){
	$count=(@array)=$_=~/$pattern.{1}/gi;
}

print "$count\n";
print "@array\n";


__DATA__
12348097790797401234790
87989871234908098098909
87987983412344908098098
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.