in reply to How am i doing?
Overall, a good start. The main some problems that i see:
Here is a version i quickly "modernized" and "cavacized". I'm note sure if the result is correct, though, since i don't have the description in the book available (and i had only a few minutes during my afternoon break to write this).
#!/usr/bin/perl # Latest perl version with the newest features and bugfixes use v5.40; # Do all kinds of automatic checking of the program code use strict; use warnings; # Great debugging tool to quickly print a complex structure (array, ha +sh, scalar, whatever) to the console use Data::Dumper; # Call the calculation main routine my $max = 100; # 4_000_000; my @baseframe = (1, 2, 3); my $result = fib($max, \@baseframe); # Call with a REFERENCE to @basef +rame, so subs can modify it # Print the final result print 'Final: ', $result, "\n"; # For debugging, print the final state of @baseframe print 'Final @baseframe: ', Dumper(\@baseframe), "\n"; # And end scene... exit(0); # This does ONE round of the calculation, no deep recursion sub fib_one_round($frame) { $frame->[0] = $frame->[0] + $frame->[1]; $frame->[1] = $frame->[2]; $frame->[3] = $frame->[2]; if(($frame->[0] %2) != 0) { return $frame->[0]; } return 0; } # This does the main loop. We are working on an array *reference*, so +fib_one_round can modify the array sub fib($max, $frame = [1, 2, 3]) { my $result = 0; # Loop until the max value has been reached while($result < $max) { $result += fib_one_round($frame); # Print the intermediate results for debugging print $result, "\n"; } return $result; }
Basically, i replaced the recursion with a while loop, added modern sub-signatures, made sure the "frame" we are working on is passed through the function calls (instead of global vars). And removed/inlined the count() function because it's a single if-statement that doesn't warrant the performance overhead of a funtion call. And, oh, added an example of Data::Dumper to show how you can easily look at complex data structures for debugging.
I also moved the main code above the subs, because that makes it easier if you come back at a later time to the code. The high level stuff is at the beginning (showing/explaining what the script does), the nitty-gritty details that you might never have to touch again are below that.
Hope that helps.
|
---|