natxo has asked for the wisdom of the Perl Monks concerning the following question:

I realize this title is weird :(, but I do not know how to express it better. Let me try. I am writing some if/elsif/else loops with the very similar content, so that got me thinking that there has to be a better way.

One of the examples I have assigns values to different HoH, and they have quite similar names: %hoh_groups_prod, %hoh_grous_test, %hoh_contacts_prod, %hoh_contacts_test. You get the idea. Theses HoH have data I want to access, I do not want to create them

So I thought: what if I create a hash, let's call it %choice, and create a table like:

my %choice = ( 'group_prod' => '$hoh_groups_prod', 'group_test' => '$hoh_groups_test', 'contacts_prod' => '$hoh_contacts_prod', 'contacts_test' => '$hoh_contacts_test', );
If I create a subroutine, then i could call

my ( $object ) = @_; my $test = $choice{ $object };
But what this does is obviously create a new variable $test and not access the values of $hoh_$object{'whatever'}

Does it make sense?

Replies are listed 'Best First'.
Re: hash value $value
by choroba (Cardinal) on Feb 17, 2016 at 15:11 UTC
    You can pass the hash reference as the argument of the subroutine (I'll call it frobnicate ):
    frobnicate(\%hoh_groups_prod);

    And, in the subroutine:

    sub frobnicate { my $hash = shift; $hash->{key} = ... ; # etc. }

    Update: \@\% (thanks LanX).

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      cool, thanks!

      Nice naming convention ;-)

Re: updated: hash value $value
by NetWallah (Canon) on Feb 17, 2016 at 17:13 UTC
    some if/elsif/else loops with the very similar content, ...

    values to different HoH, and they have quite similar names...

    This smells like you are trying to re-invent Dispatch Tables. Check out the link, to see if that is a more appealing representation/implementation.

            "Think of how stupid the average person is, and realize half of them are stupider than that." - George Carlin

      yes, strong case of NIH syndrom :-)

      I will take a look at that , thanks!

Re: hash value $value
by Anonymous Monk on Feb 17, 2016 at 15:08 UTC

    Go a few levels deeper.

    $hoh{test}{groups} = { ... }; $hoh{test}{contacts} = { ... }; $hoh{prod}{groups} = { ... }; $hoh{prod}{contacts} = { ... };