Reputation: 2574
I'm trying to get the content that was replaced (actually, removed) from the substitution function.
For example:
my $line = q{hello "my" friend "how" are 'you'};
$line =~ s/("[^"]*"|'[^']*')//g; # Removing any balanced quotes
# I'd like to print
# "my" "how" 'you'
Please be kind, I'm beginning with Perl :-).
Upvotes: 0
Views: 69
Reputation: 126742
Here's another way, using the built-in @-
and @+
arrays that hold the offsets of the latest successful match and captures.
It simply finds all the matching substrings, saves them in @removed
and deletes them using substr
.
use strict;
use warnings;
my $line = q{hello "my" friend "how" are 'you'};
my @removed;
while ($line =~ /("[^"]*"|'[^']*')/g) {
push @removed, $1;
substr $line, $-[0], $+[0] - $-[0], '';
}
print $line, "\n";
print "@removed\n";
output
hello friend are
"my" "how" 'you'
Upvotes: 0
Reputation: 98038
Instead of doing a global
substitute, you can use a loop and process each substitution:
my $line = qq(hello "my" friend "how" are 'you');
print "$1\n" while $line =~ s/("[^"]*"|'[^']*')//;
print "$line\n";
Gives:
"my"
"how"
'you'
hello friend are
Upvotes: 5
Reputation: 50657
You can use /e
regex modifier to execute code in substitution part, where $1
is being pushed into @w
array, and finally replaced by ""
empty string.
my @w;
$line =~ s/("[^"]*"|'[^']*')/ push @w,$1; "" /ge;
print "$_\n" for @w;
Upvotes: 5