G'day Latnam,
Welcome to the monastery.
" If I enter a number that is not displayed I should see - Target is not found. So for instance the number 100 is not displayed. I see - The last occurrence of 100 is at index -1."
Your problem is with this condition:
if ($search) { ...
Looking at the documentation for List::MoreUtils, under first_index, you'll see "Returns -1 if no such item could be found."; right beneath that, you'll see another function, last_index, which is probably what you want for "The last occurrence ...". [note corrected spelling]
There are two instances where $search might be FALSE: just a newline is entered at the prompt, chomp removes the newline, $search now equals ''; a zero and a newline are entered at the prompt, chomp removes the newline, $search now equals '0'. Given zero might be a perfectly valid number to search for, if you actually wanted to check that something (other than just a newline) was entered, length would be a better check (i.e. if (length $search) { ...).
Finally, writing List::MoreUtils::function_name is unnecessary: see how it's shown in the doco.
Putting all that together, here's all the elements I've discussed: you'll probably just want a subset ot these.
#!/usr/bin/env perl use strict; use warnings; use List::MoreUtils qw{first_index last_index}; my @array_to_search = qw{ 0 2 4 2 0 }; print 'Search: '; chomp( my $search = <STDIN> ); if (length $search) { my $index_1 = first_index { $_ eq $search } @array_to_search; if ($index_1 >= 0) { my $index_N = last_index { $_ eq $search } @array_to_search; print "First occurrence of '$search' at index: $index_1\n"; print "Last occurrence of '$search' at index: $index_N\n"; } else { print "'$search' not found.\n"; } } else { print "Nothing to search for!\n"; }
Some sample runs:
Search: Nothing to search for!
Search: 100 '100' not found.
Search: 0 First occurrence of '0' at index: 0 Last occurrence of '0' at index: 4
Search: 2 First occurrence of '2' at index: 1 Last occurrence of '2' at index: 3
Search: 4 First occurrence of '4' at index: 2 Last occurrence of '4' at index: 2
-- Ken
In reply to Re^4: Finding target unspecified value
by kcott
in thread Finding target unspecified value
by Latnam
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |