in reply to Index number repeating in for loop
A quick solution:
>perl -wMstrict -le "my @text = qw/A B C D E F G H I J/; ;; I: for my $i (0 .. $#text) { next I unless $text[$i] eq 'F'; print qq{$text[$i] is at index $i}; last I; } " F is at index 5
Updates: Some comments on your OPed code:
- $element = "F" This expression assigns a string to a variable. Because the assigned string is always true, the true block of the if-statement is always executed. You may have intended to test for equality, and in that case you would need to use eq to test for string equality (and not == for numeric equality): e.g. $element eq 'F'. (Already pointed out by hdb.)
- $index_number++; This statement is within the true block of the if-statement which, had you been testing for equality to 'F', would only have been executed once for the entire set of example data. You would really need to count each and every index up to the target element value in order to get a valid index.
-
$index_number You have explicitly commented out warnings and strictures in your OPed code. The $index_number variable should, IMHO, have been defined as a lexical (and perhaps even explicitly initialized to 0) outside the for-loop so it could be used inside the loop for index counting:
my $index_number = 0;
Without strictures and an explicit lexical definition, this variable is, horror of horrors, a global variable (shudder). (See johngg's second example here.)
And here's another code example using a new capability of each available for arrays since Perl version 5.12:
>perl -wMstrict -le "my @text = ('A' .. 'J'); ;; I: while (my ($i, $element) = each @text) { next I unless $element eq 'F'; print qq{$element is at index $i}; last I; } " F is at index 5
More: And here's another variation on grep as suggested by davido. Note that it does not stop when it finds the first target match, but searches all elements of the array.
>perl -wMstrict -le "my @text = qw/A B C D E F G H F I J/; ;; my @F_in_it = grep { $text[$_] eq 'F' } 0 .. $#text; ;; print qq{these indices have an 'F': @F_in_it}; " these indices have an 'F': 5 8
In Section
Seekers of Perl Wisdom