Daveid Fred
Daveid Fred

Reputation: 419

Output only last value

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);

Upvotes: 1

Views: 202

Answers (1)

Borodin
Borodin

Reputation: 126722

I suggest using a subroutine to take a chunk of code out of the loop

sub fib {
  my $n = shift();
  my @fib = (1, 1);
  push @fib, $fib[-1] + $fib[-2] while @fib < $n;
  @fib[0 .. $n-1];
}

for my $n (1 .. 5) {
  printf "%d = %s\n", $n, join ', ', fib $n;
}

Do you need to recalculate the Fibonacci series for every value in the file? If not then just move the @fib array 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-2 and move the line print "$a\n"; outside the loop to replace the line print "\n";

Upvotes: 2

Related Questions