0

I need to find value in array without iterating through whole array.
I get array of strings from file, and I need to get index of some value in this array, I have tried this code, but it doesn't work.

my @array =<$file>;
my $search = "SomeValue";
my $index = first { $array[$_] eq $search } 0 .. $#array;

print "index of $search = $index\n";

Please suggest how can I get index of value, or it is better to get all indexes of line if there are more than one entry.
Thx in advance.

1

2 Answers 2

2

What does "it doesn't work" mean?

The code you have will work fine, except that an element in the array is going to be "SomeValue\n", not "SomeValue". You can remove the newlines with chomp(@array) or include a newline in your $search string.

Sign up to request clarification or add additional context in comments.

Comments

2

Your initial question: "I need to find value in array without iterating through whole array."

You can't. It is impossible to check every element of an array, without checking every element of an array. The very best you can do is stop looking once you've found it - but you indicate in your question multiple matches.

There are various options that will do this for you - like List::Util and grep. But they are still doing a loop, they're just hiding it behind the scenes.

The reason first doesn't work for you, is probably because you need to load it from List::Util first. Alternatively - you forgot to chomp, which means your list includes line feeds, where your search pattern doesn't.

Anyway - in the interests of actually giving something that'll do the job:

while ( my $line = <$file> ) {
   chomp ( $line );
   #could use regular expression based matching for e.g. substrings. 
   if ( $line eq $search ) { print "Match on line $.\n"; last; }
}

If you want want every match - omit the last;

Alternatively - you can match with:

if ( $line =~ m/\Q$search\E/ ) {

Which will substring match (Which in turn means the line feeds are irrelevant).

So you can do this instead:

while ( <$file> ) {
   print "Match on line $.\n" if m/\Q$search\E/;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.