#!/usr/bin/perl use strict; use warnings; my @foo = 1..5; my %hash; my $ref = \%hash; for ( 0 .. $#foo ) { $ref->{ $foo[$_] } = $_ == $#foo ? undef : {}; $ref = $ref->{ $foo[$_] }; }