Chapter 3 – Your First Perl Script
April 9, 2011 in Perl, Tutorials by The Geek
Chapter 3 – Your First Perl Script
In this section we will be going over the basics of setting up and running your first Perl script. Before we continue, if you have not installed Perl on your system, download the latest MSI version from http://www.activestate.com under ActivePerl. This tutorial was written for Windows users but with minor changes it should work on Mac and Linux boxes as well.
On your desktop, right-click and select New>Text Document. Rename the file to test.pl and click enter. “.pl” is the Perl file extension. Perl files can also use the extension .cgi but that is typically reserved for Perl CGI scripts. Both work in either environment and it is not uncommon for programmers to use the .pl extension for web development.
The first line of every Perl script is called the shebang line. This line begins with the pound symbol and continues with the location of Perl on your system. If you are using Windows and did a default install of ActiveState Perl, your shebang will look like this:
#!/usr/bin/perl
Okay, let’s begin your first Perl script. Double click on your test.pl file on your desktop to open it up in Notepad for editing. If it doesn’t open in notepad, right-click the file and click Edit. Perl files, by default, open in notepad for editing.
Type in the shebang line on the first line and click enter a few times. Then enter the following infamous Hello World! Shoutout.
print “Hello World!”;
To print in Perl, whether it be information to a database or to the screen, we call upon the print command. We usually use quotes around our content and end it with a semi-colon. Nearly ALL Perl lines will end in a semi-colon and it is one of the most common mistakes made- even with programmers who’ve used Perl for years. It’s very simple to forget something as little as a semicolon.
Click on File>Save to save your script. Open up your cmd or command prompt by click on your Start icon>Run> then type in ‘cmd’ if you are on Win 2000+ or type ‘command’ if you are on an older version of windows.
To run a Perl script from your desktop, you have to travel through the command prompt to your desktop directory. Once you’re in the Desktop directly in the command line, type in
perl test.pl
The output of the script should be Hello World!. If you have successfully greeted the world, congratulations! You have written your first Perl script!