katyusza
katyusza

Reputation: 335

In perl regex replacements, how to remove leading whitespace for list elements?

I use Perl regex to search for a certain pattern, and add some new stuff immediately following it. The added stuff is a list, as commonly expected, I want each element of the list to occupy one line in the output. My code is like:

push(@happy_list, "e\n");
push(@happy_list, "f\n");
push(@happy_list, "g\n");
push(@happy_list, "h\n");

$_ = "aaa\nfoo\nbbb";
$_ =~ s/(aaa.*?bbb)/$1\n@happy_list/sg;
print;

Output result is:

aaa
foo
bbb
e
 f
 g
 h

In the output, there is a whitespace at the beginning of each element of the list, just in front of the list element. It's fine, just a little bit ugly, though. Any handy tricks to remove the extra space?

Upvotes: 0

Views: 62

Answers (3)

Sobrique
Sobrique

Reputation: 53498

First off - I'd suggest don't use $_ like that. It's a reserved variable in perl, and is used as a loop iterator. Modifying it is sometimes needed as part of the looping operation, but setting it as a shorthand for the print; statement is bad style.

The root of this problem is in stringifying an array - and it's something you don't actually need to do here anyway.

#!/usr/bin/env perl

use strict;
use warnings;

my @happy_list;

push(@happy_list, "e\n");
push(@happy_list, "f\n");
push(@happy_list, "g\n");
push(@happy_list, "h\n");

my @new_list; 
push ( @new_list, "aaa\n", "foo\n", "bbb\n" ); 
print @new_list, @happy_list;

Although, I'd probably suggest not adding the line feed, and instead:

#!/usr/bin/env perl

use strict;
use warnings;

my @happy_list;

push(@happy_list, "e");
push(@happy_list, "f");
push(@happy_list, "g");
push(@happy_list, "h");

my @new_list; 
push ( @new_list, "aaa", "foo", "bbb" ); 
print join "\n", @new_list, @happy_list;

Upvotes: 1

ersinakyuz
ersinakyuz

Reputation: 31

have you tried to trim it?

$_ =~ s/^\s+//;

Upvotes: 1

Toto
Toto

Reputation: 91488

This appens because the array is used in string context, so the default delimiter is a space.

You can change this by doing $" = ''; before the substitution.

$_ = "aaa\nfoo\nbbb";
$" = ''; #"for syntax highlighting
$_ =~ s/(aaa.*?bbb)/$1\n@happy_list/sg;
print;

You can also do:

$_ = "aaa\nfoo\nbbb";
my $str = join('', @happy_list);
$_ =~ s/(aaa.*?bbb)/$1\n$str/sg;
print;

Upvotes: 3

Related Questions