I have some code that reads from a file, and outputs the Fibonacchi numbers. E.g: 5 = 1, 1, 2, 3, 5
How can I make my code ONLY print out the last value?
Thanks
#!/usr/bin/perl
use strict;
my $fibFile = shift;
if (!defined($fibFile)) {
die "[*] No file specified...\n";
}
open (FILE, "<$fibFile");
my @numbers = <FILE>;
foreach my $n (@numbers) {
my $a = 1;
my $b = 1;
for (0..($n - 1)) {
print "$a\n";
($a, $b) = ($b,($a + $b));
}
print "\n";
}
close (FILE);
I suggest using a subroutine to take a chunk of code out of the loop
Do you need to recalculate the Fibonacci series for every value in the file? If not then just move the
@fibarray declaration outside the subroutine and the data won’t need to be recalculated.I’m sorry I didn’t answer the question! To print out only the last value in the sequence, change the loop limit in your code to
$n-2and move the lineprint "$a\n";outside the loop to replace the lineprint "\n";