basic perl problem which is annoying me, the code is: --- #!/usr/bin/perl -w
use strict; my $string; my $subString; my @indexes; print "Enter a string:\n"; chomp($string = <STDIN>); print "\nEnter substring to search for:\n"; chomp($subString = <STDIN>); ## This while loop does what i'm after #my $pos = -1; #while(1) { # $pos = index($string, $subString, $pos + 1); # find next position # print "\nPOS: $pos\n"; # last if $pos == -1; # index returns -1 if substring has no match # push @indexes, $pos; #} # Wanted to convert it to a for loop for learning # does not work like while loop for(my $pos = 0; $pos == -1; $pos++) { print "\nPOS: $pos\n"; $pos = index($string, $subString, $pos); print "\nPOS: $pos\n"; push @indexes, $pos; } if(@indexes) { print "\nLocations of '$subString' in '$string' were: @indexes\n"; } else { print "\nNo match\n"; } --- ====== Working while loop: --- my $pos = -1; while(1) { $pos = index($string, $subString, $pos + 1); # find next position print "\nPOS: $pos\n"; last if $pos == -1; # index returns -1 if substring has no match push @indexes, $pos; } --- Output example: --- [EMAIL PROTECTED]:~/storage/study/perl/LearningPerlv4/chapter13/q3$ ./ substring.pl Enter a string: stst Enter substring to search for: st POS: 0 POS: 2 POS: -1 Locations of 'st' in 'stst' were: 0 2 --- ====== Change to a for loop, only goes through once, unsure why? --- for(my $pos = -1; $pos == -1; $pos++) { print "\nPOS: $pos\n"; $pos = index($string, $subString, $pos); print "\nPOS: $pos\n"; push @indexes, $pos; } --- Output example: --- Enter a string: stst Enter substring to search for: st POS: -1 POS: 0 Locations of 'st' in 'stst' were: 0 --- ====== Change to a for loop, does not enter the loop at all, unsure why? --- for(my $pos = 0; $pos == -1; $pos++) { print "\nPOS: $pos\n"; $pos = index($string, $subString, $pos); print "\nPOS: $pos\n"; push @indexes, $pos; } --- Output example: --- Enter a string: stst Enter substring to search for: st No match --- ====== Trying to work out why: 1. the for loop does not work, want the same logic as the while loop 2. for(my $pos = -1; $pos == -1; $pos++) only iterates through once 3. for(my $pos = 0; $pos == -1; $pos++) does not enter loop at all Thanks -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/