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:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Index number repeating in for loop
by DW10 (Initiate) on Jun 28, 2013 at 21:47 UTC | |
by AnomalousMonk (Archbishop) on Jun 28, 2013 at 21:59 UTC |