use strict; use warnings; use Data::Dumper; sub add_to_hash { my $hash=my $root=(ref $_[0] ? shift : {}); my $last=pop; for my $key (@_) { $hash=($hash->{$key}||={}); die "Eeek, not a ref!" unless ref $hash; } $hash->{$last}=1; return $root; } my %hash; add_to_hash(\%hash,qw(a b c d)); add_to_hash(\%hash,qw(a c d e)); print Dumper(\%hash);