Md at debian.org

tales of a debian maintainer

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";

About

This is the blog of Marco d'Itri.

S M T W T F S
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31    

See also:

My blogroll:


W3C HTML 4.01
W3C CSS 2.0     

Powered by Bryar.pm.