How to test if a value exist in a hash?

后端 未结 6 1326
-上瘾入骨i
-上瘾入骨i 2020-12-08 12:20

Let\'s say I have this

#!/usr/bin/perl

%x = (\'a\' => 1, \'b\' => 2, \'c\' => 3);

and I would like to know if the value 2 is a ha

6条回答
  •  春和景丽
    2020-12-08 12:53

    Everyone's answer so far was not performance-driven. While the smart-match (~~) solution short circuits (e.g. stops searching when something is found), the grep ones do not.

    Therefore, here's a solution which may have better performance for Perl before 5.10 that doesn't have smart match operator:

    use List::MoreUtils qw(any);
    if (any { $_ == 2 } values %x) {
        print "Found!\n";
    }
    

    Please note that this is just a specific example of searching in a list (values %x) in this case and as such, if you care about performance, the standard performance analysis of searching in a list apply as discussed in detail in this answer

提交回复
热议问题