in reply to Hashes and arrows
%AppCode is not a nested hash here. It's a separate hash altogether.
This:
$TotCst{$AppCode{$ID}}Could have been written as:
my $this_appcode = $AppCode{$ID}; $TotCst{ $this_appcode }
It's just taking a value from one hash, and using that value as the key to another hash.
Your original:
$TotCst{$AppCode{$ID}}->{$CstType{$ID}} += $InvAmnt{$ID};Could have been written as:
my $this_appcode = $AppCode{$ID}; my $this_csttype = $CstType{$ID}; $TotCst{$this_appcode}->{$this_csttype} += $InvAmnt{$ID};
So what does the arrow operator actually do? Well, confusingly it performs two different duties in Perl. The first is for object oriented programming: it's the method call operator:
$object->method(@arguments); Class->method(@arguments);
But that's not how it's being used here. Here it's the dereferencing operator.
# Here's an array... my @array = ('foo', 'bar', 'baz'); # Set up a reference (pointer) to the array above. my $array_ref = \@array; # We can access an item in the array like this. warn $array[2]; # But we want to access it via the reference (pointer) # then we need the arrow: warn $array_ref->[2];
What's happening here? The arrow operator takes the thing on the left, which is a reference (pointer) to some other piece of the data, follows the reference to find the data, and then applies whatever's on the right hand side.
So in the example above, it's following the $array_ref pointer to find @array then it's applying the index [2] to it.
As it happens, the arrow is actually optional in your case. This should work just as well:
$TotCst{$this_appcode}{$this_csttype} += $InvAmnt{$ID};
This is because inside hashes and arrays, any nested hashes/arrays will always be references, so it is unambiguous that they will always need to be dereferenced. In my $array_ref->[2] example, the arrow operator is not optional.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Hashes and arrows
by enttoobad (Novice) on Mar 14, 2012 at 09:01 UTC |