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

This is a bit of an obfuscation question. Say you have this program:
my $string = '12 abcdefghijklmnopqrstuvwxyz'; my ($len) = ($string =~ /^(\d+)/; my ($substring) = ($string =~ /^\d+ (.{$len})/); print "$substring\n";
Is there a way to combine the two regexps? for example, something like
my ($len,$substring) = ($string =~ /^(\d+) (.{$1})/);
(except we know that doesn't work)? Having it all on one line in one regexp is the goal...

Thanks!

Replies are listed 'Best First'.
Re: Using previous match in the same matching regexp
by GrandFather (Saint) on Nov 16, 2005 at 22:48 UTC
    use warnings; use strict; my $string = '12 abcdefghijklmnopqrstuvwxyz'; $string =~ s/^(\d+) (.*)/substr $2, 0, $1/e; print "$string\n";

    Prints:

    abcdefghijkl

    DWIM is Perl's answer to Gödel
Re: Using previous match in the same matching regexp
by Roy Johnson (Monsignor) on Nov 16, 2005 at 23:04 UTC
    my ($len,$substring) = ($string =~ /^(\d+) ((??{qr".{$1}"}))/);
    perlre explains the experimental postponed-regexp feature.

    Caution: Contents may have been coded under pressure.
      Tightening up just a wee bit more...
      my ($len,$substring) = ($string =~ /^(\d+) ((??{".{$1}"}))/);
Re: Using previous match in the same matching regexp
by ikegami (Patriarch) on Nov 16, 2005 at 23:10 UTC
    If you need a solution that doesn't clobber $string:
    $substr = $string =~ /^(\d+) (.*)/ && substr($2, 0, $1);
    If you need both $len and $substring:
    ($len, $substr) = $string =~ /^(\d+) (.*)/ && ($1, substr($2, 0, $1));
Re: Using previous match in the same matching regexp
by japhy (Canon) on Nov 17, 2005 at 03:57 UTC