Perl: Matching hash keys to a regular expression

前端 未结 4 1729
渐次进展
渐次进展 2020-12-10 11:38

I\'m wondering if Perl has a built-in way to check for the existence of a hash element with a key matching a particular regex. For example:

my %h = ( \'twelv         


        
4条回答
  •  眼角桃花
    2020-12-10 12:05

    The smart match operator does this (available since Perl v5.10).

    $a      $b        Type of Match Implied    Matching Code
    ======  =====     =====================    =============
    ...
    Regex   Hash      hash key grep            grep /$a/, keys %$b
    ...
    

    Sample usage:

    # print if any key in %h ends in "teen"
    print "We have some teens\n" if /.*teen$/ ~~ %h;
    

提交回复
热议问题