http://qs321.pair.com?node_id=267634

sschneid has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

I'm working on message threading, and could use a bit of help. Here's a sample data structure I'm working on outputting:
Data strucure: Message ID (Parent) -- 1 (0) |-- 2 (1) \-- 3 (1) |-- 4 (3) | \-- 6 (4) \-- 5 (3)
The output doesn't really have to look exactly like that; the indenting is really the only part I'm concerned about.

So, at the moment, I have some sample data (just CSV right now, no need to be pulling from an actual database until I have this working the way I'd like) that I've put into a hash:
# Get the data and store it in a message hash while (<DATA>) { chomp(my ($id,$thread,$from,$date,$content) = split /,/); %{$msg->{$id}} = ( thread => $thread, from => $from, date => $date, content => $content ); }
So far, so good. This is the part where I'm a bit stuck as far as the best way to sort the data. Is having the message's parent ID enough? Can I efficiently output based on that? I have code (see below) to create another key in the hash (which children each message has), but I'm unsure as to whether this is really necessary or not. I figure I'll be looping through the message hash to display the output, and looping through it twice just to have the children listed in the hash might be unnecessary since we already know each message's parent. In any case, here's that code:
foreach my $id (keys %{$msg}) { next if ($msg->{$id}->{thread} == 0); push @{ $msg->{ $msg->{$id}->{thread} }->{children} }, $id; }
So, I'm stuck. Any help would be appreciated. Thanks.

-s.