get Perl hash keys part of a string/regex without a loop? -


i'm not sure how phrase question in single line, here need:

i need element of hash key "subset" of given string. if hash is

%h = ( 'ab' => 1, 'cd' => 2); 

and string abc123, ab hash.

i know do

$str = 'abc123'; foreach (keys %h) {     print "$_ \n" if $str =~ m/^$_/; } 

but i'm asking if there's more efficient way, way work if matching other way around

%h = ('abc123' => 1, 'def456' => 2); print "$_ \n" grep /^ab/, keys %h 

well can hide loop inside call grep, in second example

my %h = ( ab => 1, cd => 2 ); $str = 'abc123';  print "$_\n" grep { $str =~ /^$_/ } keys %h; 

but there little or no speed advantage

if wanted find one of hash keys build regex them, this

my $re = join '|', sort { length($b) <=> length($a) } keys %h; $re = qr/$re/; 

and find first matching hash key this

print "$1\n" if $str =~ /^($re)/; 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -