use strict; use warnings; use YAML qw/Dump/; my %parent_of; my %tree; my %ref; while() { chomp; my ($parent, $child) = split /,/; $parent_of{$child} = $parent; my $h; if(exists $parent_of{$parent}) { $h = $ref{ $parent }; $h->{$child} = {}; $ref{$child} = $h->{$child}; } else { $h = \%tree; $ref{$parent} = $h; $h->{$parent}{$child} = {}; $ref{$child} = $h->{$parent}{$child}; } } print Dump(\%tree) . "\n"; __DATA__ 1,3 1,4 1,5 3,8 3,9 4,11 4,18 8,14 8,15 5,17 5,16 17,21