Jump to content

Perl Programming/First programs

From Wikibooks, open books for an open world
Previous: Getting started Index Next: Basic variables

A first taste of Perl

[edit | edit source]

Here's a simple program written in Perl to get us started:

#!/usr/bin/perl

# Outputs Hello World to the screen.
 
print "Hello World!\n";

Let's take a look at this program line by line:

  • #!/usr/bin/perl
On Unix systems this tells the Operating System to execute this file with the program located at /usr/bin/perl. This is the default Unix location for the perl interpreter, on Windows #!C:\Perl\bin\perl.exe or #!C:\strawberry\perl\bin\perl.exe (depending on whether ActivePerl or Strawberry Perl was installed) should be used instead.
Shebang: A line at the start of a file, beginning with #!, that gives instructions to the operating system.
  • # Outputs ...
This line is a comment - it is ignored by the perl interpreter, but is very useful. It helps you to debug and maintain your code, and explain it to other programmers.
Comment: A line of plain text ignored by the interpreter in a file of code.
  • print "Hello World!\n";
The print instruction writes whatever follows it to the screen. The \n at the end of the string puts a new line to the screen. The semicolon at the end of the line tells the perl interpreter that the instruction is finished; you must put a semicolon at the end of every instruction in Perl code.
String: A sequence of characters used as data by a program.

Exercises

[edit | edit source]
  • Change the program so it says hello to you.
  • Change the program so that after greeting you, it asks how you are doing, on the next line. The output should look like this:
Hello your_name!
How are you?
  • Experiment with the \n character, what happens when you take it away? What happens, if you put two in a row?

Remember: If you add another print instruction you will need to put a semicolon after it.

Previous: Getting started Index Next: Basic variables