use strict; use warnings; use List::Util qw/max/; my $graphspec = '1 -> 2 2 -> 0 3 -> 4 4 -> 2 5 -> 10 6 -> 10 7 -> 9 8 -> 9 9 -> 6 10 -> 4 11 -> 10 12 -> 10 13 -> 12 14 -> 10 15 -> 2'; my %graph; while ($graphspec =~ /(\d+)\s+->\s+(\d+)/g) { $graph{$1} = $2; } sub depth { return max map { $_and 1 + depth($graph{$_}) } @_; } print depth(keys %graph);