Reputation: 147
I have some substring [ aa bb cc ]
in a line, like $line = "1 2 a b [ aa bb cc ] c d [ bb cc ] 3 4"
. And I want to trim all the spaces in these substrings. The following code does not work.
while($line =~ /\[(.*?)\]g/)
{
$1 =~ s/\s+//g;
}
Can someone help please
Upvotes: 3
Views: 332
Reputation:
Your method fails because the match variable $1
is read-only. You can use non-destructive substitution (introduced in Perl 5.16) to avoid that problem:
use warnings;
use strict;
my $line = "[foo bar] [ baz ] sproing";
while($line =~ /\[(.*?)\]/g)
{
my $result = $1 =~ s/\s+//gr;
print "|$result|\n";
}
Upvotes: 0
Reputation: 97918
Another way similar to your attempt:
while($line =~ s/\[([^\]\s]*)\s+/[$1/g) {}
and you don't have to escape the r-square bracket, but it helps vim.
Upvotes: 2