grepping thru hashref

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

In the following code i want to grep for a number ($num)  held in
If a match is found the program should which key in %toplist_hash
contains the number. The question really boils down to how to use
grep to access an element of an array ref inside a hash

my %toplist_hash = (
           'LTest' => [
           'Friday' => [

$num = '60403';
for (keys %toplist_name) {
     if (grep(/^$num$/, @})) {
         print $_;

Re: grepping thru hashref

monkeys paw schrieb:
Quoted text here. Click to load it

The algorithm is quite OK, you just need to make sure that you
don't change variable names halfway down.
"toplist_hash" ne "toplist_name"
but a simple "use warnings;" would have explained the problem
to you.
_Always_ test your code with 'use strict;' and 'use warnings;'.


Re: grepping thru hashref

Quoted text here. Click to load it
Quoted text here. Click to load it

You have both for and grep setting $_. Since grep can't be changed, you
need to tell for to use a different variable. Also, if these are numbers
you should probably be using numeric equality (and not quoting them).

    for my $k (keys %toplist_hash) {
        if (grep $num == $_, @}) {
            print $k;

If you know there's only one matching key, add a 'last' after the
'print' so you don't search the rest of the keys. If you are going to be
doing this at all often, build a reversed hash like

    my %toplist_num;
    for my $k (keys %toplist_hash) {
        for my $n (@}) {
            $toplist_num = $k;

so you can perform the lookup directly.


Re: grepping thru hashref

Thanks both of you. The reverse hash list is excellent advice.

Quoted text here. Click to load it

Site Timeline