Reputation: 337
I have the following code:
use strict;
use warnings;
my $find = "(.*\s+)(subject:)(.*)(_1)(\s+.*)";
my $replace = '"\nsubject: \t\t$3_2"';
my $var_1 = "Time: 1000-1200 subject: Physic_1 Class: Room A";
my $var_2 = "Time: 1000-1200 subject: Math_1 Class: Room A";
$var_1 =~ s/$find/$replace/ee;
$var_2 =~ s/$find/$replace/ee;
print $var_1."\n";
print $var_2."\n";
I expect the output only extract the subject and change _1 to _2 like:
Output:
subject: Physic_2
subject: Math_2
However, what I get is:
Output:
Unrecognized escape \s passed through at test.pl line 20.
Unrecognized escape \s passed through at test.pl line 20.
Time: 1000-1200 subject: Physic_1 Class: Room A
Time: 1000-1200 subject: Math_1 Class: Room A
How can I escape those \t, \s+, \n as on string variable as perl regex pattern?
UPDATE: If I do something like this:
my $pattern = 's/(.*\s+)(subject:)(.*)(_1)(\s+.*)/\nsubject: \t\t$3_2/g';
my $var = "Time: 1000-1200 subject: Physic_1 Class: Room A";
$var =~ $pattern;
print $var."\n";
It give the output, seem like nothing change:
Time: 1000-1200 subject: Physic_1 Class: Room A
Upvotes: 0
Views: 5614
Reputation: 242383
Double quotes interpolate backslashed characters. \s
has a special meaning in a regex, but not in doublequotes - hence the warning. Use single quotes instead.
my $find = '(.*\s+)(subject:)(.*)(_1)(\s+.*)';
or, if you need double quotes for some other reasons, double the backslashes that should survive in the regex:
my $find = "(.*\\s+)(subject:)(.*)(_1)(\\s+.*)";
Upvotes: 4
Reputation: 26763
You can do that in the first line exactly as you did it in the second line:
my $find = '(.*\s+)(subject:)(.*)(_1)(\s+.*)';
Output:
subject: Physic_2
subject: Math_2
Upvotes: 0