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

i'm trying to abstract some regexes for a dispatch routine as such:
my %patterns = { { 'regex' => qr/^\/section\/([\d]{1,8})[\/]?$/, 'function' => 'do__section', 'id_fields' => ['section_id'] } }
i can match fine, but my issue is this:
i'd like to loop through @{$patterns{'id_fields'}} , and call an object with a dictionary of the arguments

something like:
my @fields = @{$$regex_set{'id_fields'}}; unshift @fields, ''; my %args; for ( my $i=1; $i<=$#fields ; $i++ ) { $args{$fields[$i]} = $$i; }
unfortunately, $$i doesn't work (which would be $1)
i need some method of addressing $1,$2 dynamically - can anyone offer a suggestion>

Replies are listed 'Best First'.
Re: regex question - dynamically address captures
by GrandFather (Saint) on Feb 21, 2006 at 23:00 UTC

    The following may be what you want. Note the @captures = map... line in particular.

    use warnings; use strict; use Data::Dump::Streamer; my %patterns = ( pattern1 => { 'regex' => qr'^/section/([\d]{1,8})/?$', 'function' => 'do__section', 'id_fields' => ['section_id'] }, pattern2 => { 'regex' => qr'^/para/([\d]{1,8})/?$', 'function' => 'do__para', 'id_fields' => ['para_id'] } ); my @lines = ('/section/123', '/para/256'); for my $line (@lines) { for my $key (keys %patterns) { next if $line !~ /$patterns{$key}->{regex}/; my @captures = map {substr $line, $-[$_], $+[$_] - $-[$_] + 1} 1.. +$#-; my %args; @args{@{$patterns{$key}->{'id_fields'}}} = @captures; print "Dump for $key:\n"; Dump (\%args); } }

    Prints:

    Dump for pattern1: $HASH1 = { section_id => 123 }; Dump for pattern2: $HASH1 = { para_id => 256 };

    DWIM is Perl's answer to Gödel

      Nice, but you should replace

      next if $line !~ /$patterns{$key}->{regex}/; my @captures = map {substr $line, $-[$_], $+[$_] - $-[$_] + 1} 1..$#-;

      with the much simpler

      my @captures = $line =~ /$patterns{$key}->{regex}/ or next;

        Argh. I had the equivelent of that first off, but I'd used 1 for the section and para numbers so @captures contained a single element with the value 1 and I convinced myself that it was the match count.

        Candidate for OT: most egregious programming error, ever maybe? :)


        DWIM is Perl's answer to Gödel
        a_ AWESOME. thank you both.

        b_ the +1 on the substr should be cut.
        Your response and Grandfather's have solved an important problem for me on my day job. Thank you, fellow monks!

        Jim Keenan