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

In this example:
if ($string =~ /ab|ac|ad|ba|bla|etc/) {print $1}

is there a way to find the position of match? In the above example if match will be "ac", position number is 2.

Replies are listed 'Best First'.
Re: position number
by toolic (Bishop) on Sep 18, 2013 at 18:37 UTC
    You might want something like:
    use warnings; use strict; my @pats = qw(ab ac ad ba bla etc); my %pos; @pos{ @pats } = 1 .. @pats; my $re = join '|', @pats; $re = qr/$re/; while (<DATA>) { print "$1 $pos{$1}\n" if /($re)/; } __DATA__ fable fact

    Output:

    ab 1 ac 2
Re: position number
by Happy-the-monk (Canon) on Sep 18, 2013 at 18:12 UTC

    if ($string =~ /ab|ac|ad|ba|bla|etc/) {print $1}

    I guess you meant to write if ($string =~ /(ab|ac|ad|ba|bla|etc)/) {print $1}

    ... with a set of parantheses around what you want to match.

    There's index to tell the position of a substring in a string.

    Cheers, Sören

    Créateur des bugs mobiles - let loose once, run everywhere.
    (hooked on the Perl Programming language)

Re: position number
by Laurent_R (Canon) on Sep 18, 2013 at 19:06 UTC

    The @- special variable contains the start offset of the match and submatches. Possibly what you are looking for.

      Requisite link for the OP: @- from perlvar.


      #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

        Yes, this is what I'm looking for. Thanks.

      TIL:

      my $re = join '|', map "($_)", qw[ab ac ad ba bla etc]; for (qw[tab act mad bar blank fetch]) { printf "%-6s %-4s %d\n", $_, $+, $#- if /$re/; }

      Output:

      tab ab 1 act ac 2 mad ad 3 bar ba 4 blank bla 5 fetch etc 6
      Thanks to all specially to Laurent_R and kennethk. The @- is what I'm looking for.