Perl compilers for various operating systems are available at: perl.org



Example Program
  1. # Perl Example Program
  2. # Input: An integer, $listlen, where $listlen is less
  3. # than 100, followed by $listlen-integer values.
  4. # Output: The number of input values that are greater than
  5. # the average of all input values.
  6.  
  7. ($sum, $result) = (0, 0);
  8. $listlen = <STDIN>;
  9.  
  10. if (($listlen > 0) && ($listlen < 100)) {
  11. # Read input into an array and compute the sum
  12. for ($counter = 0; $counter < $listlen; $counter++) {
  13. $intlist[$counter] = <STDIN>;
  14. } #- end of for (counter ...
  15.  
  16. # Compute the average
  17. $average = $sum / $listlen;
  18.  
  19. # Count the input values that are > average
  20. foreach $num (@intlist) {
  21. if ($num > $average) { $result++; }
  22. } #- end of foreach $num ...
  23.  
  24. # Print result
  25. print "Number of values > average is: $result \n";
  26.  
  27. } #- end of if (($listlen ...else {
  28. print "Error--input list length is not legal \n";
  29. }


Readability Example

A simple script to search a file for a string and print the 2 lines above and below it.

Perl identifies it's variables with $, making it easy to determine which words in the code are variables or which are commands. The syntax of perl follows many patterns set by more commonly used languages such as C or C++.

  1. # read the whole file into memory.
  2. open(FILE, "<myText.txt");
  3. @array = <FILE>;
  4. close(FILE);
  5.  
  6. # specify which string to find.
  7. $stringToFind = "no time left";
  8.  
  9. # iterate over the array looking for the
  10. # string. The $#array notation is used to
  11. # determine the number of elements in the
  12. # array.
  13. for ($index = 0; $index <= $#array; $index++) {
  14. last if $array[$index] =~ /$stringToFind/;
  15. }
  16.  
  17. # Use $index to print two lines before
  18. # and two lines after the line that contains
  19. # the match.
  20. foreach (@array[$index-2..$index+2]) {
  21. print("$index: $_");
  22. $index++;
  23. }