#!/usr/bin/perl # http://perlmonks.org/?node_id=1138357 use strict; use warnings; $_ = < 8000 1 /second/example/for/testing 8001 8000 END my (%pids, %memoize); $pids{$2} = [$3, $1] while /^(\s*(\d+)\s+(\d+).*\n)/gm; sub trace { $memoize{$_[0]} //= do { my ($ppid, $line) = @{ $pids{shift()} }; ($ppid ? trace($ppid) : "\n") . $line; } } print trace $_ for /^\s*(\d+)\s+\d+\s+/gm;