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

hello! Monks, can any one tell me , which is the best way to match which of two strings occurs first in a text
  • Comment on out of two strings which occurs first in a text

Replies are listed 'Best First'.
Re: out of two strings which occurs first in a text
by ikegami (Patriarch) on Sep 24, 2008 at 07:02 UTC

    index

    my $posa = index($str, $stra); my $posb = index($str, $strb); if ($posa < 0 || $posb < 0) { print("$stra doesn't occur\n") if $posa < 0; print("$strb doesn't occur\n") if $posb < 0; } elsif ($posa < $posb) { print("$stra first occurs before $strb\n"); } elsif ($posa > $posb) { print("$strb first occurs before $stra\n"); } else { print("$stra and $strb first occur at the same location\n"); }

    Update: Added missing braces.

Re: out of two strings which occurs first in a text
by lamp (Chaplain) on Sep 24, 2008 at 08:27 UTC
    Use regex. For eg.
    #!/usr/bin/perl -w use strict; my $str = "is the best way to match which of two strings occurs first +in a text"; my $first = "two"; my $second = "match"; $str =~ m/($first|$second)/g; print $1 if($1); # $1 will hold first matched value
    If it matches any string, the special variable '$1' will hold the first match.

      Four bugs.

      • The g is an error.
      • You treat the contents of $first and $second as patterns.
      • if($1) doesn't work. $1 is not erased on a failed match.
      • if($1) doesn't work. $1 could be spaces or zeroes.

      Fix:

      my ($earliest) = $str =~ /(\Q$first\E|\Q$second\E)/; print( "$earliest\n" ) if defined( $earliest );

      Update: Added 4th bug.

        Add another possible bug.   If, for example,  $first contains  'pat' and  $second contains  'pattern' then  $first will always match first.

      I am also in favour of your regex approach, but you must take care that neither of these strings contain characters which have special meaning within a regex.

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James