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

I'm using the function  index to find the position of a couple of stopping strings. Say I have 3 different stopping strings. ie.  $end1, $end2, $end3 In a file I need to find the first occurence of either one. Could I do something like this.
$startcod = index($seq, $start); print "$startcod\n"; $endcod = index($seq, $end1 || $end2 || $end3, $startcod); print "$endcod\n";
Or is there another way to do it. Thanks!

Replies are listed 'Best First'.
Re: finding position of first occurence of 3 different stopping criteria
by Not_a_Number (Prior) on Sep 21, 2003 at 19:53 UTC

    You could try something like this:

    my $seq = "012345678WW89YYabcdeZZ"; my $start = 'WW'; my @ends = qw (XX YY ZZ); my $end = '(' . join ( '|', @ends ) . ')'; if ( $seq =~ /$start.*?$end/ ) { print "start: $-[0] end: $-[1]"; }

    dave

Re: finding position of first occurence of 3 different stopping criteria
by kvale (Monsignor) on Sep 21, 2003 at 19:35 UTC
    Try a regexp:
    my $extract = $1 if $text =~ /^(.*?)($end1|$end2|$end3)/;

    -Mark

      If you just want the position of the start of match, then it's as easy as:
      print "Matched at $-[1]\n" if $text =~ /^.*?($end1|$end2|$end3)/;
      See perlvar for @- and @+ variables.

      Update: and this is along the same lines as Not_a_Number's post below. sorry for the redundancy...

Re: finding position of first occurence of 3 different stopping criteria
by shenme (Priest) on Sep 21, 2003 at 20:01 UTC
    Getting back to capturing what matched and where, but use Not a Number's way of constructing the inner match:
    my $s2 = '$endcod = index($s2eq, $end1 || $end2 || $end3, $s2tart +cod);'; while( $s2 =~ m/(end|dex|art)/g ) { printf " Found '%s' at %d\n", $1, pos($s2); }
    Outputs:
      Found 'end' at 4
      Found 'dex' at 15
      Found 'end' at 27
      Found 'end' at 36
      Found 'end' at 45
      Found 'art' at 55