my %calls; #has all the function call information my $length = 3; #the length of function chains my @chain_store; #array of array, to save the chains while (($key, $value) = each %calls) { my @chain = (); push @chain, $key; get_chains($value, \@chain); } sub get_chains { my $value = shift; my $chain_ref = shift; my @chain = @{$chain_ref}; foreach my $val @{$value} { push @chain, $val; my $is_present = 1; for (my $count = 0; $count < $length; $count++) { if (exist($calls{$val})) { get_chains($calls{$val}) } else { $is_present = 0; last; } } if ($is_present) { push @chain_store, @chain; } } }