3

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

3 Answers 3

7
s{\[(.*?)\]}{
   my $s = $1;
   $s =~ s/\s+//g;
   $s
}eg;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. However, I got some error with this code:Backslash found where operator expected at ../convtag.pl line 11, near "$s =~ s/\" (Might be a runaway multi-line // string starting on line 9) (Missing operator before \?) Global symbol "$s" requires explicit package name at ../convtag.pl line 9. Global symbol "$s" requires explicit package name at ../convtag.pl line 9. syntax error at ../convtag.pl line 11, near "$s =~ s/\" Substitution pattern not terminated at ../convtag.pl line 11.
@ikegami interesting substitution notation
2

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.

Comments

0

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";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.