#!/usr/bin/perl use strict; use Data::Dumper; my @arr = qw(comp1-cmd1-test1 comp1-cmd1-test2 comp1-cmd2-test1 comp2-cmd1-test1 comp2-cmd1-test2 comp3-cmd1-test1); my $ret_struct; foreach my $element (@arr) { my ($comp, $cmd, $test) = split(/\-/, $element); push(@{$ret_struct->{$comp}{$cmd}}, $test) unless(grep(/$test/, @{$ret_struct->{$comp}{$cmd}})); push(@{$ret_struct->{$cmd}}, $test) unless(grep(/$test/, @{$ret_struct->{$cmd}})); } print Dumper($ret_struct); #### $VAR1 = { 'cmd2' => [ 'test1' ], 'comp2' => { 'cmd1' => [ 'test1', 'test2' ] }, 'comp3' => { 'cmd1' => [ 'test1' ] }, 'cmd1' => [ 'test1', 'test2' ], 'comp1' => { 'cmd2' => [ 'test1' ], 'cmd1' => [ 'test1', 'test2' ] } };