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; } #### 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"; #### 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";