fork download
  1. #!/usr/bin/perl
  2.  
  3. # Idiom #315 Memoization
  4.  
  5. my %cache;
  6. sub fib {
  7. my $n = shift;
  8. return $cache{$n} if exists $cache{$n};
  9. return $cache{$n} = $n if $n < 2;
  10. return $cache{$n} = fib($n-1) + fib($n-2);
  11. }
  12.  
  13. print "\n\nCustom memoized implementation\n";
  14. foreach my $n ( 1..10 ) {
  15. print ' ' . fib( $n );
  16. }
  17.  
Success #stdin #stdout 0.01s 5396KB
stdin
Standard input is empty
stdout

Custom memoized implementation
 1 1 2 3 5 8 13 21 34 55