#!/bin/perl5 use strict; use warnings; my %hash=(); %hash=( "M01.001" => 0, "M01.001.111" => 0, "M01.001.111.111" => 0, "M01.002" => 0, "M01.002.003" => 0 ); my %HoA; for my $k ( keys %hash ){ $k =~ /(M\d{2}\.\d{3})/; my $parent = $1; push @{$HoA{$parent}}, $k } foreach my $parent ( sort keys %HoA ) { print "$parent\n"; foreach my $i ( 0 .. $#{$HoA{$parent}} ) { my $child = $HoA{$parent}[$i]; next if $parent eq $child; print "\t$child\n"; } print "\n"; } #### M01.001 M01.001.111 M01.001.111.111 M01.002 M01.002.003