# As long as we have multiple keys, access the next subhash while (@keys > 1) { my $key = shift @keylist; $hashref = $hashref->{$key}; } #### while (@keylist > 1) { my $key = shift @keylist; $hashref = $hashref->{$key}; } #### use strict; use warnings; use Data::Dump; my %testhash; my $hr = \%testhash; my $count = 0; while() { print "[", join('-',split ' ', $_), "]\n"; add_val( $hr, ++$count, split ' ', $_); } dd \%testhash; sub add_val { my ($hashref, $val, @keylist) = @_; die "Expected a list of keys!" unless @keylist; die "Expected a hashref!" unless "HASH" eq ref $hashref; # As long as we have multiple keys, access the next subhash while (@keylist > 1) { my $key = shift @keylist; $hashref = $hashref->{$key}; } # Now set the value $hashref->{shift @keylist} = $val; } __DATA__ a1 a2 a3 jjj kkk lll mmm Output: [a1-a2-a3] [jjj-kkk-lll-mmm] {} #### Output: [a1-a2-a3] [jjj-kkk-lll-mmm] { a1 => { a2 => { a3 => 1 } }, jjj => { kkk => { lll => { mmm => 2 } } }, }