Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to understand how this can be rewritten in more simplistic syntax for better understanding. Is hash2 being assigned as a value for key $a in hash1 then assigned as an array in @sub?
my $sub = $hash1{$a} = $hash2{$b}; push @$sub, $a;
|
|---|
| Replies are listed 'Best First'. | |||
|---|---|---|---|
|
Re: Hash to Array assignment?
by kcott (Archbishop) on Oct 31, 2013 at 06:27 UTC | |||
"I'm trying to understand how this can be rewritten in more simplistic syntax for better understanding." In my opinion, some of your biggest barriers, with respect to making this more understandable, are the poor choice of variable names: Beyond the naming issues, if you're encountering (associativity) difficulties with:
Then don't do it! This works the same and is abundantly clearer:
Consider these two versions of your code. As you've provided no context or other indication of the data involved, I've had to contrive names: I'm sure you can do better.
As you can see from the output, the functionality is the same in both pieces of code:
There are occasions (e.g. for reasons of efficiency) where hard-to-read, minimalist code is needed. These situations are not the norm; when they do arise, feel free to add copious comments to explain each and every nuance that you think may not be fully understood. Do bear in mind that code you write today may appear crystal clear; when you revisit it at some time in the (not necessarily distant) future, it may be less obvious than it once was. -- Ken | [reply] [d/l] [select] | ||
|
Re: Hash to Array assignment?
by Athanasius (Archbishop) on Oct 31, 2013 at 02:40 UTC | |||
Consider:
Output:
First, the %hash2 value with key $b is assigned to the %hash1 value with key $a. Next, this value (which in my example code is an array reference) is assigned to $sub. Finally, $a is pushed onto the array referenced by $sub. Hope that helps,
| [reply] [d/l] [select] | ||