Jordan
Jordan

Reputation: 1614

Test if a string contains the key of a hash in Perl

I have a string and want to tell if it contains the key of a hash and if it does I would like to print the value of the hash like so:

#!/usr/bin/perl -w

my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1\n";
if ($str contains a key of %h){
    print the value of that key; #i.e v1
}

Whats the best way to do this? (Preferably concise enough to contain in an if statement)

Upvotes: 1

Views: 1833

Answers (3)

salva
salva

Reputation: 10244

In some cases (big hash, keys are words and you don't want them to match sub-words) this could be the right approach:

my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1 and key3 but notkey2, at least not alone\n";

while ($str =~ /(\w+)/g) {
    my $v = $h{$1};
    print "$v\n" if defined $v;
}

Upvotes: 1

tobyink
tobyink

Reputation: 13664

If you have to search through multiple strings but have just the one unchanging hash, it might be faster to compile the hash keys into a regexp upfront, and then apply that regexp to each string.

my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $hash_keys = qr/${\ join('|', map quotemeta, keys %h) }/;

my @strings = (
   "this is a string containing key1\n",
   "another string containing key1\n",
   "this is a string containing key2\n",
   "but this does not\n",
);

foreach my $str (@strings) {
   print "$str\n" if $str =~ $hash_keys;
}

Upvotes: 3

Amadan
Amadan

Reputation: 198368

#!/bin/perl -w

my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1\n";
while (($key, $value) = each %h) {
  if (-1 != index($str, $key)) {
    print "$value\n";
  }
}

Upvotes: 5

Related Questions