next up previous contents index
Next: Programming Elements Up: Physics 2101 - Scientific Previous: Contents   Contents   Index


A Perl Program

There are two main steps in running a Perl program: It must be stressed that this file is a text (ascii) file. Word processors such as Microsoft Word are inconvenient to use for this purpose, as by default they save files in their own (binary) format. Life will be easier in your programming career if you start off with a text-only editor, such as emacs or xemacs.

A simple Perl program that just prints out something to the terminal screen is

  # file hello.pl (this is a comment)
  print "Hello, world!\n";
Note the trailing semi-colon at the end - this indicates to Perl the end of the command. Anything after the ``#'' sign is treated as a comment by the interpreter, and thus ignored. Generally spaces or line breaks are ignored by the interpreter - the above program could also be written as
  print 
             "Hello, world!\n"      ;
although for human eyes this is less readable.

After creating this file, save it as, for example, hello.pl, and run it through the Perl interpreter (the "pl" extension is used in some contexts to indicate the type of file). Running it through the interpreter can be done through a terminal window as

  C:\> perl hello.pl
This assumes that perl is in your PATH environment variable.

On Unix there is a shortcut you can use to run such programs. Modify the above file so that it includes a shebang line as the first line:

  #!/usr/bin/perl
  print "Hello, world!\n";
This line will indicate to the shell that the program found as /usr/bin/perl will be used to carry out the commands that follow. On Unix it is often customary to name such files without an extension, so save this file, for example, as simply hello. After this, you can make the file executable by
   bash$ chmod u+x hello
You can then run the file as
  bash$ hello
If the current directory is not in your PATH environment variable, you would have to run this as
  bash$ ./hello

next up previous contents index
Next: Programming Elements Up: Physics 2101 - Scientific Previous: Contents   Contents   Index