Archive

Posts Tagged ‘Backreferences’

Retrieving an unknown number of backreferences

July 28th, 2008 John No comments

I have been racking my brains over this, but could not find help anywhere. It seems that doing wacky stuff in Perl out of desperation actually pays off!

I wanted to search a string using this regexp without knowing how many matches I would find:

$string =~ /\(\d+):/g

This would match ‘15′  and ‘20′ in a string which looks like this :

$string = "(yeast:0.12313,((zebrafish:0.12312,fugu:0.84134)15:0.52313,
human:0.94424)20:0.93313);";

One can access the found values by using backreferences (in this case $1 and $2). But what if you do not know how many backreferences there are?

This piece of perl code will return the values of all the backreferences:

my @array;
while ($string =~ /\)(\d+):/g) {
push @array, $1;
}

@array will contain the values of all the backreferences. Don’t ask me why this works…