Reputation: 57
I have this match
$line =~ s/(.*?$)/$1\n(\s){$array[0]}/;
which gives the error
Unrecognized escape \s passed through
Can someone tell me why using the $1
is throwing this error. In my text editor, the colours also change if I add or remove the $1
(the colours signify when a character is specially interpreted).
Also, is (\s){$array[0]}
the correct way of saying I want spaces that many times (the number in $array[0]).
Thanks.
Upvotes: 1
Views: 326
Reputation: 54381
The right hand side of a substitution s///
is not a regular expression pattern. You cannot tell it to create content by using pattern syntax.
Unrecognized escape \s passed through at ...
This error means that Perl interpreted the \s
as a escape sequence similar to \n
or \r
inside an interpolated string. The right hand side of the substitution is the same as a normal double quoted ""
string. \s
does not have a meaning there, so Perl complains. All the brackets and parenthesis will show up as literal characters. When run with the data I've provided further down in the answer, this is the result.
foo
(s){4}
Instead, you will have to use the /e
flag on your substitution, and provide Perl code. The right hand side of the s///
will be evaluated with actual code, and the result will be used as the substitution. You can use the x
operator to repeat your blank space character. Note that the whole right hand side now needs to be a valid Perl expression, so you have to construct strings and use the concatenation operator .
.
$line =~ s/(.*?$)/"$1\n" . ( q{ } x $array[0] ) /e;
When I run this with an underscore instead of a space it looks weird though. I don't think it does what you want.
my @array = ( 4 );
my $line = "foo";
$line =~ s/(.*?$)/"$1\n" . ( "_" x $array[0] ) /e;
print $line;
__END__
foo
____
Upvotes: 4