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

I am trying to match the first occurance of a pattern match in a string with that pattern's position in the string.
#!/usr/bin/perl -w use strict; my $variable = "123g 321 123 g 321"; if ($variable =~ /g/) { #need the position of the first g here #which, should be 3 }
Any ideas, without touching each character in the string?

Replies are listed 'Best First'.
Re: Matching pattern in regular expression with string position
by BrowserUk (Patriarch) on Aug 09, 2003 at 12:46 UTC

    Within the if statement,

    my $pos = pos( $variable ) - 1;

    should do the trick.

    See perlfunc:pos for more information.

    You might also look at perlvar:$+ * pervar:$-, but these are only set when captiring brackets are used.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
    If I understand your problem, I can solve it! Of course, the same can be said for you.

      Either pos() or $-[0]. You could also write that as my $pos = $-[0].

      In order for pos() to work, he'll need to add a /g modifer. It only works on "global" matches.

      Also, it's not the scalars $+ and $- which would be of interest but the arrays @+ and @- which would be. Finally, $+[0] and $-[0] are both useful even without any capturing because they hold offsets from the entire match.

      In his case, $-[0] is exactly what he needs.

      -sauoq
      "My two cents aren't worth a dime.";
      
Re: Matching pattern in regular expression with string position
by Not_a_Number (Prior) on Aug 09, 2003 at 13:43 UTC

    You could also use the index function:

    my $pos = index $variable, 'g';

    dave