Search code examples
perlforeachsubroutineref

perl using subroutine as argument of a foreach


my %number_words = hash_a_file($_);
foreach my $key ( keys %number_words ) {
    ++$word_list{$key};
}

This is working but I would like to avoid using the intermediate variable like this

foreach my $key ( keys hash_a_file($_) ) {
    ++$word_list{$key};
}

I tried to use refs but still failed. Any way to do this ? Thanks !


Solution

  • The thing is, a subroutine doesn't return a hash. It returns a list. In your original code, it only becomes a hash when you store it in a hash variable.

    But there are other ways to create a hash from a list. You can create an anonymous hash and then de-reference it. It's ugly, but it works.

    # Inner braces create an anonymous hash.
    # Outer braces de-reference that into a "real" hash
    foreach my $key ( keys %{ { hash_a_file($_) } } ) {
        ++$word_list{$key};
    }
    

    Update: To back up Borodin's comment, I should add that if this code was presented to me in a code review, I'd suggest rewriting it to use an explicit hash variable as your original code does.