PERL - Lesson 1 : Introduction and Hello World

Introduction

I always believe everyone can write programs and enjoy building computer applications. With this goal in mind, I am planning to write few posts during my free times about programming concepts and how I really understood these concepts. I will use Perl programming language as the guide and explain these concepts.

PERL - Practical Extraction and Report Language

Positive features:
  • Scripting language - No compiling
  • System administration - easier to use syntax than shell script
  • Easy to parse text content and extract information using regular expression
  • Few lines of code compared to Java or C++ 
  • Object-Oriented concepts - version > 5.0

1. Hello world program

The first step in learning any new program is writing a script to print hello world. Here is how it is done in Perl

a. From a file
create a file hello_world.pl

#!/usr/bin/perl 
use strict;
use warnings;

# print statement
print "hello world!\n";
  1. first line - She-bang character used to identify the interpreter (Perl)
  2. '#' in the beginning of the line represetn comment
  3. 'use' is used for loading libraries - strict and warnings should be used as good practice to dump out errors or warnings generated by Perl interpreter - variable declaration.
  4. 'print' command to print string.
  5. every line should end with semicolon. 
In the command-prompt.
M_BCBB_10017:~ vivek$ perl hello_world.pl 
hello world!

M_BCBB_10017:~ vivek$ chmod 775 hello_world.pl # make the code exectuable
M_BCBB_10017:~ vivek$ ./hello_world.pl 
hello world!

b.  from command prompt
M_BCBB_10017:~ vivek$ perl -e 'print "hello world!\n;"'
hello world!

2. Checking Perl Version

Perl comes already installed in UNIX, LINUX or Mac OS X operating system. You can check the version of perl installed in your computer by typing 'perl -v' in the command-prompt. I used my MacBookPro laptop with Mac OS X (10.6) with Darwin Kernel(10.4.0). If you are using Windows operating system then you have to download and install ActivePerl(http://www.activestate.com/activeperl/downloads) from ActiveState

-command-prompt$ perl -v
This is perl, v5.10.0 built for darwin-thread-multi-2level
(with 2 registered patches, see perl -V for more detail)

Copyright 1987-2007, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.