fork download
  1. #!/usr/bin/perl
  2.  
  3. # Functions in Perl are called subroutines. Like bash, you don't define the
  4. # parameters in the function declaration. We'll see how to access the parameters
  5. # when we look at the Fibonacci subroutine below.
  6.  
  7. sub main {
  8.  
  9. # Again, the ubiquitous printf function. Apparently a staple of programming
  10. printf "\nHow many numbers of the sequence would you like?\n";
  11.  
  12. # Once again, we don't need to declare variables before using them.
  13. # Perl's scalar variables, prefaced with $, can be either strings or numbers
  14. # We use <STDIN> to get the data from stdin here
  15.  
  16. $n = 10;
  17.  
  18. # As in PHP, we need to remove the newline at the end
  19.  
  20. chop $n;
  21.  
  22. &fibonacci($n);
  23.  
  24. exit 0;
  25. }
  26.  
  27. # Except for the first line declaring the subroutine, and the different way that
  28. # parameters passed to the subroutine are passed, this is identical to the PHP version
  29.  
  30. sub fibonacci {
  31. $a = 0;
  32. $b = 1;
  33.  
  34. # So now we see the parameter being used here. For clarity, I have written the for
  35. # loop using $n like the other examples. To set $n using the first parameter passed
  36. # to the subroutine, I access the scalar variable $_[0], which is the first element
  37. # of the parameter array @_
  38.  
  39. $n = $_[0];
  40.  
  41. for ($i=0;$i<$n;$i++){
  42. printf "%d\n", $a;
  43. $sum = $a + $b;
  44. $a = $b;
  45. $b = $sum;
  46. }
  47. }
  48.  
  49. &main;
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
===SORRY!===
Unsupported use of C-style "for (;;)" loop; in Perl 6 please use "loop (;;)" at line 41, near "($i=0;$i<$"
stdout
Standard output is empty