Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Not finding anything in perlre or perlrequick, nor in Sacred Tome of the Ram, I come to you, Monks of Perl, for assistance in interpreting the language arcane. I seek to extract multiple results from a regular expression (from an extant scalar) in the least amount of perl code:

Replies are listed 'Best First'.
Re: Best way to extract RE backreferences
by tall_man (Parson) on Feb 05, 2003 at 19:36 UTC
    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.

      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.

Re: Best way to extract RE backreferences
by Abigail-II (Bishop) on Feb 05, 2003 at 23:36 UTC
    Least amount of code? As in "Perl golf"? Try:
    @x="abcdefg"=~/[bcd]/g

    Abigail

Re: Best way to extract RE backreferences
by Anonymous Monk on Feb 06, 2003 at 21:40 UTC
    I just wanted to thank you all for the assistance and insight you've provided. It has been most helpful to realize I have been ignorant of my studies of the sacred list context, a tragedy seen times before. Alas, I leave the monestary in shame.