Reputation: 662
I have a big hash with a lot of elements.
%my_hash = ();
# filling of %my_hash automaticly
$my_variable;
# set the value of $my_variable within a loop
Now I want to find the value of $my_variable
within %my_hash
. I tried it with
if(grep {/$my_variable/} keys %my_hash){
$my_new_variable = #here should be the element of %my_hash which makes the statement true
}
how to do that?
Edit: The problem is not the whole $my_variable
will be find at %my_hash
, e.g.
$my_variable = astring
$modules_by_path{"this_is_a_longer_astring"} = (something)
now I want to find this...
Upvotes: 0
Views: 155
Reputation: 50637
If you're looking only for one particular key from %my_hash
,
if (my ($my_new_variable) = grep /\Q$my_variable/, keys %my_hash) {
..
}
or
if (my @keys = grep /\Q$my_variable/, keys %my_hash) { .. }
if there are more keys which match specified regex. (use \Q
prefix if $my_variable
is not regex but literal string to be matched).
Upvotes: 2
Reputation: 126722
You can use grep
, but you need to put it in scalar context to get the result you want. You also need to escape the contents of $my_variable
if there's any chance that it contains any regex metacharacters.
This uses \Q
to escape the non-alphanumeric characters, and leaves all the hash keys that match in @matching_keys
. It's up to you to decide what to do if there's more than one match!
my @matching_keys = grep /\Q$my_variable/, keys %my_hash;
I suspect that there's a better way to do this. It's spoiling the whole point of hashes to search through them like that, and I think a better data design would help. But I can't say any more unless you describe your data and your application.
Upvotes: 1
Reputation: 59
if you want to match every key of your hash, you have to iterate through them in a loop as well. this is how i would do it, don't know if it is the most elegant way though:
#!/usr/bin/env perl
use strict;
use warnings;
my %hash = (
foo => 1,
bar => 1,
baz => 1,
);
my $variable = "bar";
my $new_variable;
for my $key (keys %hash){
if ($key =~ /$variable/){
$new_variable = $hash{$key};
}
}
print $new_variable, "\n";
also, always try to write stuff like that with use strict; it will spare you of many classic mistakes.
Upvotes: 0