Question

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 :-).

Was it helpful?

Solution

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;

OTHER TIPS

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 

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'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top