Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard for hash element in Perl

I am trying to check if a certain hash element exists. I have two keys for the hash:

if (exists $hash{$key1}{*})
{
then do blabla
}

So, where the * is, I would like to use a wildcard (i.e., that value can be anything). What is/are the wildcard charachter(s) for Perl in a situation like this? Many thanks!

like image 690
Abdel Avatar asked Jan 03 '12 12:01

Abdel


2 Answers

There are no wild card characters.

You can get a list of the keys like so:

my @keys_in_hash = keys %{ $hash{key1} };

…which you can then check to see if it has a length, test using grep or whatever.

like image 99
Quentin Avatar answered Nov 19 '22 08:11

Quentin


Your original code

if (exists $hash{$key1}{*})
{
then do blabla
}

If you want to check if the second level hash contains any keys, then you can do this

if (%{$hash{$key1}}) {
    # do blabla
}

If you want to pick up all keys which match a pattern, say all keys that begin "foo", then you could do this:

my @matching_keys = grep m/^foo/so => keys %{$hash{$key1}};

if (@matching_keys) {
    # do something
    # matching values are in @{$hash{$key1}}{@matching_keys}
}
like image 21
zgpmax Avatar answered Nov 19 '22 07:11

zgpmax