http://www.perlmonks.org?node_id=967223


in reply to Re: Parenthesis grouping into regexes.
in thread Parenthesis grouping into regexes.

Here is an example with data made up to match your regular expressions. Are you sure about the fourth colon in $ip6?

use strict; use warnings; my $ip4 = qr !(?: [0-9]{1,3}\.){3} [0-9]{1,3} !x; my $ip6 = qr !(?: [a-f0-9]{4}:)+ !x; my $prefix = qr ! / \d \d !x; my $pattern = qr ! ^($ip4|$ip6) ($prefix)? !x; while (<DATA>) { next if $_ !~ $pattern; print "Hey, I found \$1: $1 \$2: $2\n"; } __DATA__ no match here 999.888.777.666/66 aaaa:aaaa:aaaa:aaaa:/77

Replies are listed 'Best First'.
Re^3: Parenthesis grouping into regexes.
by aramisf (Beadle) on Apr 26, 2012 at 18:45 UTC
    Labelling groups (with (?pattern) regex) showed me what was happening. It is all clear now.

    Many thanks to everyone, specially BillKSmith!

    I was having a trouble when using $1, $2... because I didn't know they exact behaviour.

    The problem I had was with the parenthesis inside $ip4 regex, causing $2 to have an ip address,
    $3 had the match inside the parenthesis in $ip4, and the prefix I expected put into $4:
    # Example of my debug output: line = '*> 177.101.16.0/21 200.19.74.230 0 200' matches: $1:'*> ' $2:'177.101.16.0' $3: '16.' $4:'/21'

    Now I understand how $1, $2, $3... are set.
    Thank you all, Monks! =D