Data strucure: Message ID (Parent) -- 1 (0) |-- 2 (1) \-- 3 (1) |-- 4 (3) | \-- 6 (4) \-- 5 (3) #### # Get the data and store it in a message hash while () { chomp(my ($id,$thread,$from,$date,$content) = split /,/); %{$msg->{$id}} = ( thread => $thread, from => $from, date => $date, content => $content ); } #### foreach my $id (keys %{$msg}) { next if ($msg->{$id}->{thread} == 0); push @{ $msg->{ $msg->{$id}->{thread} }->{children} }, $id; }