# File: searchAllsub2.pl # Title: Given string and a substring (pattern) # Capture all the positions of the substring in string # use system function: pos($seq) - gives next position # C:\myPerl>perl searchAllsub.pl # There are 3 positions where 'at' is found in mathematica Result: 1 6 ### Find positions for a in mathematicat *** $seq = 'mathematica'; $regex = 'at'; #search substring 'at' in mathematica @Places = searchAll($seq,$regex); #call subroutine $Places = @Places; # find length array result print "\nThere are ", $Places, " positions where $regex is found in $seq: ", @Places; exit; ### Subroutine, takes 2 args: sequence and a substring and return list of positions ### sub searchAll { my @Positions = (); # initialize array where you put positions my ($s,$r) = @_; # array of arguments from main program: sequence and character while ( $s =~ m/$r/g ) { # search globally (g) pattern $r is $s # you have to subtract length of pattern to find its start position push (@Positions,pos($s)-length($r)); # add to list of positions } return @Positions; }