Guest User

Untitled

a guest
Jul 21st, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use 5.010;
  5.  
  6. # Closure = Object with 1 method
  7. # Hash + Closures = Object with more than 1 method
  8.  
  9. sub fibby {
  10. # some initial state
  11. my($a,$b) = (0,1);
  12. # and our methods
  13. my $object = {
  14. # a 'method' for giving us the next fibonacci number
  15. move_forward => sub {
  16. ($a,$b) = ($b,$a+$b);
  17. $a;
  18. },
  19. # and another one for moving backwards
  20. move_back => sub {
  21. ($a,$b) = ($b-$a,$a);
  22. $a;
  23. }
  24. };
  25. }
  26.  
  27. my $fibonacci_object = &fibby();
  28. say "First lets move forward.";
  29. foreach my $i (1..10) {
  30. # the notation for 'method' calls is a little ugly but that's because I'm a perl newbie
  31. say "F_$i is ", &{$fibonacci_object->{move_forward}}();
  32. }
  33.  
  34. say "Now lets move back.";
  35. foreach my $i (reverse (1..9)) {
  36. say "F_$i is ", &{$fibonacci_object->{move_back}}();
  37. }
Add Comment
Please, Sign In to add comment