#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @arr = qw(aa bb cc dd ee ff); sub build { my %hash; my $ref = \%hash; while (defined (my $element = shift @_)) { $ref = ($ref->{$element} = @_ ? {} : 0); } \%hash; } print Dumper build(@arr);