So, the question, as I mentioned above and as you saw in the sub, how does the subroutine know it's container hash key, in order to calculate the right key's qty values?
Various ways.
my %phrases = ( "phrase 1" => { qty => 1, qtySum => 5, qtyCont => 8, }, "phrase 2" => { qty =>10, qtyCont =>34, }, "phrase 3" => { qty =>1, }, ); for my $k (keys %phrases) { # update # $phrases{$_}->{ qtyTotal} = sub { qtyTotal($_) } $phrases{$k}->{ qtyTotal} = sub { qtyTotal($k) } } sub qtyTotal{ my $qty = 0; my $key = shift; my $phObj = $phrases{$key}; foreach my $qType ('qty', 'qtySum', 'qtyCont'){ $qty += $phObj->{$qType} if exists $phObj->{$qType}; } return $qty; }
That way the subroutine qtyTotal() doesn't need to know about %phrases and could be in a different scope. And you could e.g. have "aliases" in your %phrases hash, saying $phrases{"phrase 4"} = $phrases{"phrase 2"}.for my $k (keys %phrases) { # update # my $ref = $phrases{$_}; my $ref = $phrases{$k}; $ref->{ qtyTotal} = sub { qtyTotal($ref) } } sub qtyTotal{ my $qty = 0; my $phObj = shift; foreach my $qType ('qty', 'qtySum', 'qtyCont'){ $qty += $phObj->{$qType} if exists $phObj->{$qType}; } return $qty; }
print "${ \$phrases{'phrase 2'}->{'qtyTotal'}->() }\n";
This approach has the advantage that you can add more methods (e.g. qtyAverage()) to the Qty class and use them without having to change the way in which you populate %phrases.package Qty; sub new { my $class = shift; bless { @_ }, $class; } sub qtyTotal { my $phObj = shift; foreach my $qType ('qty', 'qtySum', 'qtyCont'){ $qty += $phObj->{$qType} if exists $phObj->{$qType}; } return $qty; } package main; my %phrases = ( "phrase 1" => Qty->new( qty => 1, qtySum => 5, qtyCont => 8, ), "phrase 2" => Qty->new( qty =>10, qtyCont =>34, ), "phrase 3" => Qty->new( qty =>1, ), ); print "${ \$phrases{'phrase 2'}->qtyTotal() }\n";
As a rule of thumb - if you ask yourself how does X know it's Y, the object approach suits best.
In reply to Re: How to detect a hash container key from a referenced sub value
by shmem
in thread How to detect a hash container key from a referenced sub value
by igoryonya
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |