my @list = f( a => [ 'b', 'c' ], b => [ 'c', 'd' ], c => [ 'd' ], e => [ 'b', 'a' ], f => undef, ); sub f { $h{$_}||=[]for map@$_,%h=@_; sub x { my$x=1; $x+=x($_)for@{@h{@_}||[]}; $x } sort{x($a)<=>x$b}keys%h }