Regexp capture group list

Paul LeoNerd Evans leonerd at leonerd.org.uk
Tue Nov 10 13:51:28 GMT 2009


On Tue, Nov 10, 2009 at 02:37:59PM +0100, Philip Newton wrote:
> But you could try this:
> 
> sub parse
> {
>   my ( $text, $re ) = @_;
>   my @matches = $_[0] =~ /^$re// or die "Expected $re in $text...\n";
>   $_[0] =~ s/^$re//;
> 
>   return @matches
> }
> 
> at the cost of running the regexp twice (once for matching and
> capturing, then once for substituting).

Ooh; but wait a moment.. we can do better... $+[0] contains the string
index of the end of the match. The leading ^ means it must have been at
the start.

So how about

  my @matches = $_[0] =~ m/^$re/ or die ....;
  substr( $_[0], 0, $+[0] ) = "";

  return @matches;

I think I like that...

-- 
Paul "LeoNerd" Evans

leonerd at leonerd.org.uk
ICQ# 4135350       |  Registered Linux# 179460
http://www.leonerd.org.uk/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: Digital signature
Url : http://london.pm.org/pipermail/london.pm/attachments/20091110/c607c5c8/attachment.pgp


More information about the london.pm mailing list