in reply to out of two strings which occurs first in a text

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.

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

    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.

        True, but this is one of those cases where the bug is in the requirements as much as the implementation - what is the desired result in this case?

        --
        .sig : File not found.

        That behaviour surprised me so I checked it out. You're right, but I would have expected the greediness of perls's regexp matching to favour the longer string. Interesting.
Re^2: out of two strings which occurs first in a text
by CountZero (Bishop) on Sep 24, 2008 at 09:21 UTC
    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