-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?

Royeh
  • 433
  • 5
  • 21

1 Answers1

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.

reinierpost
  • 8,425
  • 1
  • 38
  • 70
rbm
  • 3,243
  • 2
  • 17
  • 28
  • 2
    `any` from [List::Util](http://perldoc.perl.org/List/Util.html#any) 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 Nov 02 '15 at 10:10
  • @ThisSuitIsBlackNot Would you please send your comment as a answer? – Royeh Nov 02 '15 at 10:15
  • 2
    @Royeh No, because it has already been used in answers on at least 3 duplicate questions: http://stackoverflow.com/q/720482/176646, http://stackoverflow.com/q/4570650/176646, http://stackoverflow.com/q/2860226/176646. No reason to add it here, too. – ThisSuitIsBlackNot Nov 02 '15 at 10:20