-1

Maybe my question is really easy, but I would like to know the best way and efficient one.

Let's we have an array of strings and we want to compare it with another string. say,

my @array = {"hi","bye","you","shadow", "hi"}

Now I want to check if at least one element of the array equals hi then there is some condition. May I know your idea about it. I know that within a for loop one could do it easily, but Would you would suggest as a good one?

1
  • 1
    Use grep on the array? Commented Nov 2, 2015 at 10:01

1 Answer 1

1

Something like

my @array = qw (hi bye you shadow hi);
my $hi_count = scalar(grep {$_ eq 'hi'} @array);
print $hi_count;

This will print 2 as there are two words that equal hi.

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

3 Comments

any from List::Util is better for large arrays since it will return as soon as a match is found; grep will loop through every single array element no matter what.
@ThisSuitIsBlackNot Would you please send your comment as a answer?
@Royeh No, because it has already been used in answers on at least 3 duplicate questions: stackoverflow.com/q/720482/176646, stackoverflow.com/q/4570650/176646, stackoverflow.com/q/2860226/176646. No reason to add it here, too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.