Using a variable name as the key name in a hash (Perl) -


this question has answer here:

i have block of perl code want simplify. it's part of subroutine, series of arguments added values hash of hashes.

$user{$account_num}{'item0'} += $item0; $user{$account_num}{'item1'} += $item1; $user{$account_num}{'item2'} += $item2; $user{$account_num}{'item3'} += $item3; $user{$account_num}{'item4'} += $item4; $user{$account_num}{'item5'} += $item5; $user{$account_num}{'item6'} += $item6; 

you can see variable names same key names. seem remember watching friend kind of thing in 1 line once. like:

[looping through input arguments]: $user{$account_num}{'variable_name'} += $variable_name; 

does know of way this?

you're on thinking it.

i can tell because of time:

me: if make device can vibrate socket right frequency, can cause bulb screw , unscrew. can attach device socket...

my son: dad, why don't use light switch?

if have bunch of items called item1, item2, item3, etc. why not make array of items? have $item[0], $item[1], etc. simplify code:

for item ( @items ) {     $user{$account_name}->[$item] += $items[item]; } 

maybe using item1 , item2 stand-ins actual variable names. maybe they're $widget , $left_handed_smoke_shifter. in case, can make hash of items, have $item{left_handed_smoke_shifter} , $item{widget}. then, loop this:

for $item ( keys %items ) {     $user{$account_name}->{$item} += $items{$item}; } 

simple, easy understand , maintain.

however, if really, insist need able use variable names way insist, use eval:

$user{$account_name}->{$varible_name} = eval '$' . "$variable_name"; 

i sell lengths of ropes long enough hang it. none of business.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -