Sun, 14 Oct 2007
Bug or feature? s/// and the g option
I recently discovered some perl behaviour that I cannot explain. My goal in this code was to get the matched string in $1. I see how only having a scalar for multiple possible matches (the result of g) could be a problem, but I expected to alyway get something. The effect instead is that $1 may or may not be defined, depending on apparently unrelated changes like setting the i option or changing the regexp in a way which does not alter the matched text.
My test case follows.
#!/usr/bin/perl
use warnings;
use strict;
#use re 'debugcolor';
my $text = <<END;
XXWY
XXWZ
END
# $1 is defined only if I remove either of ?, g or i
my $count = $text =~ s#(XXW?Y)##gi;
print "REMOVED: <<$1>>\nCOUNT: $count\n";