Perl Basics   «Prev  Next»

Lesson 4 Perl: compiled or interpreted?
ObjectiveDiscover how the Perl language is a little bit compiled and a little bit interpreted.

Is Perl compiled or interpreted?

It used to be a truism that compiled languages were inherently faster than interpreted languages. This is no longer the case. The Perl interpreter is no longer an interpreter in the strictest sense of the term.
The program, perl (as distinguished from the language, Perl), takes the Perl language source and compiles it internally in intermediate steps. This makes perl a cross between a compiler and an interpreter with some of the characteristics of each. It also makes perl fast.
Perl is an interpreted language, not a compiled language. This means that the code written in Perl is executed directly by the interpreter, without the need for a separate compilation step. The Perl interpreter reads the source code and executes it line by line, allowing for quick development and testing.



As a demonstration, I wrote a simple routine that calculates the factorial of a number (n) in both C and Perl.
(The factorial of n is n times n - 1 times n - 2...times 1.)
Perl factorial program.
#!/usr/bin/perl
$CRLF = "\x0d\x0a";
print "Content-type: text/plain$CRLF$CRLF";

# print factorials from 0 to 9
for( $i = 0; $i <= 9; $i++) { 
  print "the factorial of $i is " . fact($i) . "\n";
}

sub fact{
  my $number = $_[0];
  return $number unless $number > 1;
  $number * fact($number - 1);
}

This is the same program in C:
#include <stdio.h>
double fact(int number);

void main (int argc, char ** argv ){
  int number;
  int i;
  /* print factorials from 0 to 9 */
  for(i = 0; i <= 9; i++) {
    number = i * 10;
   printf("the factorial of %d is %1.14e\n", 
    number, fact(number));
  }
}

double fact(int number){
  if(number <= 1) { 
    return number; 
  }
  else { 
    return number * fact(number - 1); 
  }
}

The following page discusses the difference between Compilation and Interpretation.
How to build Perl on Android 4