#! perl -slw use strict; use Data::Dump qw[ pp ]; sub x; sub x{ my $ref = shift; my @keys = sort keys %{ $ref }; return unless @keys; return join ',', map { my $leafs = x( $ref->{ $_ } ); $leafs ? "($leafs)$_" : $_ } @keys; } my %tree; while( ) { chomp; my $key; my $ref = \%tree; my @nodes = split ';', $_; $key = shift @nodes, $ref = $ref->{ $key } //= {} while @nodes; } pp \%tree; print x( \%tree ); __DATA__ a; a;b; a;b;e; a;b;f; a;c; a;c;g; a;c;h; a;c;h;i; a;c;h;j; a;d; #### C:\test>815486 { a => { b => { e => {}, f => {} }, c => { g => {}, h => { i => {}, j => {} } }, d => {}, }, } ((e,f)b,(g,(i,j)h)c,d)a