Reputation: 6521
I have a text, where I would like find all matchings
(e.g. every pattern which match /d.g/
)
Those patterns I need in a list and removed from original text.
Operation on: dog and dig where dug in dug
should give me:
(dog, dig, dug, dug).
The text should change to: and where in
I could do It by passing the text twice, but it would be double work?
Upvotes: 2
Views: 114
Reputation: 126722
I would write it like this
use strict;
use warnings;
my $str = 'dog and dig where dug in dug';
my @matches;
push @matches, substr $str, $-[0], $+[0] - $-[0], '' while $str =~ /d.g/g;
print join(', ', @matches), "\n";
print $str, "\n";
output
dog, dig, dug, dug
and where in
Upvotes: 0
Reputation: 185171
Try doing this :
$_ = 'dog and dig where dug in dug';
(/\b(d.g)\b/) ? push @_, $1 : print "$_ " for split /\s+/;
print "\n\narr:\n", join "\n", @_;
\b
is word boundaries(condition) ? 'if true' : 'if false'
statement is a ternary operatorUpvotes: 0
Reputation: 6204
Here's another option:
use strict;
use warnings;
my $str = 'dog and dig where dug in dug';
my @matches;
$str =~ s/\b(d.g)\b/push @matches, $1; ''/ge;
print $str, "\n";
print join ', ', @matches;
Output:
and where in
dog, dig, dug, dug
Upvotes: 3