Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use 5.010;
- # Closure = Object with 1 method
- # Hash + Closures = Object with more than 1 method
- sub fibby {
- # some initial state
- my($a,$b) = (0,1);
- # and our methods
- my $object = {
- # a 'method' for giving us the next fibonacci number
- move_forward => sub {
- ($a,$b) = ($b,$a+$b);
- $a;
- },
- # and another one for moving backwards
- move_back => sub {
- ($a,$b) = ($b-$a,$a);
- $a;
- }
- };
- }
- my $fibonacci_object = &fibby();
- say "First lets move forward.";
- foreach my $i (1..10) {
- # the notation for 'method' calls is a little ugly but that's because I'm a perl newbie
- say "F_$i is ", &{$fibonacci_object->{move_forward}}();
- }
- say "Now lets move back.";
- foreach my $i (reverse (1..9)) {
- say "F_$i is ", &{$fibonacci_object->{move_back}}();
- }
Add Comment
Please, Sign In to add comment