Reputation: 8917
my $test = "_.4.1\n";
print $test;
my $docid=4;
$test =~ s/_.$docId.1/_.$docId.0/gm;
print $test
I was hoping to see:
_.4.1
_.4.0
But I get:
_.4.1
_.4.1
Upvotes: 1
Views: 110
Reputation: 132811
Perl 5.10 has a nice feature that makes this problem easier. a \K
in the pattern portion of the substitution operator tells it to not replace anything before the \K
. That way, you can make the pattern to locate the bit that you want to change, but then only replace the part that doesn't change:
use v5.10;
use strict;
use warnings;
my $test = "_.4.1";
say $test;
my $docId=4;
$test =~ s/_\.$docId\.\K1/0/;
say $test;
I removed the /g
and /m
flags because they don't do anything in your example.
If you aren't using v5.10 yet (and it's one of the unsupported versions now), you can get the same effect with a positive lookbehind (as long as it's a constant width pattern):
use strict;
use warnings;
my $test = "_.4.1";
print "$test\n";
my $docId = 4;
$test =~ s/(?<=_\.$docId\.)1/0/;
print "$test\n";
Upvotes: 1
Reputation: 67900
You have a capital I
in $docId
in your regex, but declare it with a lower case i
. $docid
is not considered the same variable as $docId
. Perl differentiates between upper and lower case inside variable names.
You should always use
use strict;
use warnings;
To prevent simple errors like this.
See also: Why use strict and warnings?
Upvotes: 8
Reputation: 1379
Try using the -w option in perl
_.4.1
Use of uninitialized value $docId in regexp compilation at test.pl line 4.
_.4.1
$docid != $docId;
Upvotes: -1