in reply to Best way to extract RE backreferences

Here's a handy shortcut:
my ($b, $c, $d) = ($str =~ /(b)(c)(d)/);
If a match is done in list context it returns a list of the backreference matches.

Replies are listed 'Best First'.
Re: Re: Best way to extract RE backreferences
by Fletch (Bishop) on Feb 05, 2003 at 19:51 UTC

    Strictly speaking the parens around the match itself aren't necessary; it's already in list context.

    % perl -le '$_="abcde";my($z,$y,$x)=/(b)(c)(d)/;print "$x$y$z"' dcb

    However if you wanted to save only a subset of the saved subexpressions, the ()'s around the match will let you use brackets to get a slice (but then you might be better off using non-capturing parens instead).

    my( $y, $x ) = (/(b)(c)(d)/)[1,2];
      However if you wanted to save only a subset of the saved subexpressions, the ()'s around the match will let you use brackets to get a slice (but then you might be better off using non-capturing parens instead).

      <nit>Maybe. You might have a large parsing regex that's been compiled with /o and you want the 3rd through 9th columns of 12 columns.</nit>

      ------
      We are the carpenters and bricklayers of the Information Age.

      Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

        Your objection is valid but you shouldn't be using /o anymore. We have qr() now.

        Makeshifts last the longest.