in reply to Find the boundaries of a substring in a string

My example will give you the start and end positions without using regex. I did some testing, and it appears that this solution runs much slower than the regex solution. But it's just to show that there is more than one way to do it :

#!/usr/bin/perl use strict; use warnings; my @STARTPOS = (); my @ENDPOS = (); my $str = "BaaaaBBBBBBaaaaaaaBBBBBBBBBBBBBBBBBBBBaaaBBBBBBBBBBBxB"; print "$str\n\n"; my $i = 0; while (($i = index($str, 'B', $i)) >= 0) { push(@STARTPOS, $i++); while (vec($str, $i++, 8) == 66) {} push(@ENDPOS, $i-1); } # Display results: for (my $i = 0; $i < @STARTPOS; $i++) { print "\nstart: ", $STARTPOS[$i], "\t-> end: ", $ENDPOS[$i]; }

Replies are listed 'Best First'.
Re^2: Find the boundaries of a substring in a string
by Anonymous Monk on Jun 28, 2023 at 18:22 UTC
    So a worse way, coding perl like C, defeating the purpose, but with much worse performance. Awesome