ASPN ActiveState Programmer Network
  ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups | Web Services
SEARCH
advanced | search help

Reference
ActivePerl 5.10
Core Documentation
perl
perlintro
perltoc
perlreftut
perldsc
perllol
perlrequick
perlretut
perlboot
perltoot
perltooc
perlbot
perlstyle
perlcheat
perltrap
perldebtut
perlfaq
perlfaq1
perlfaq2
perlfaq3
perlfaq4
perlfaq5
perlfaq6
perlfaq7
perlfaq8
perlfaq9
perlsyn
perldata
perlop
perlsub
perlfunc
perlopentut
perlpacktut
perlpod
perlpodspec
perlrun
perldiag
perllexwarn
perldebug
perlvar
perlre
perlrebackslash
perlrecharclass
perlreref
perlref
perlform
perlobj
perltie
perldbmfilter
perlipc
perlfork
perlnumber
perlthrtut
perlothrtut
perlport
perllocale
perluniintro
perlunicode
perlunifaq
perlunitut
perlebcdic
perlsec
perlmod
perlmodlib
perlmodstyle
perlmodinstall
perlnewmod
perlpragma
perlutil
perlcompile
perlfilter
perlglossary
perlembed
perldebguts
perlxstut
perlxs
perlclib
perlguts
perlcall
perlreapi
perlreguts
perlapi
perlintern
perliol
perlapio
perlhack
perlbook
perlcommunity
perltodo
perldoc
perlhist
perldelta
perl5100delta
perl595delta
perl594delta
perl593delta
perl592delta
perl591delta
perl590delta
perl588delta
perl587delta
perl586delta
perl585delta
perl584delta
perl583delta
perl582delta
perl581delta
perl58delta
perl573delta
perl572delta
perl571delta
perl570delta
perl561delta
perl56delta
perl5005delta
perl5004delta
perlartistic
perlgpl
perlcn
perljp
perlko
perltw
perlaix
perlamiga
perlapollo
perlbeos
perlbs2000
perlce
perlcygwin
perldgux
perldos
perlepoc
perlfreebsd
perlhpux
perlhurd
perlirix
perllinux
perlmachten
perlmacos
perlmacosx
perlmint
perlmpeix
perlnetware
perlopenbsd
perlos2
perlos390
perlos400
perlplan9
perlqnx
perlriscos
perlsolaris
perlsymbian
perltru64
perluts
perlvmesa
perlvms
perlvos
perlwin32

MyASPN >> Reference >> ActivePerl 5.10 >> Core Documentation
ActivePerl 5.10 documentation

NAME

perlintro -- a brief introduction and overview of Perl


DESCRIPTION

This document is intended to give you a quick overview of the Perl programming language, along with pointers to further documentation. It is intended as a "bootstrap" guide for those who are new to the language, and provides just enough information for you to be able to read other peoples' Perl and understand roughly what it's doing, or write your own simple scripts.

This introductory document does not aim to be complete. It does not even aim to be entirely accurate. In some cases perfection has been sacrificed in the goal of getting the general idea across. You are strongly advised to follow this introduction with more information from the full Perl manual, the table of contents to which can be found in the perltoc manpage.

Throughout this document you'll see references to other parts of the Perl documentation. You can read that documentation using the perldoc command or whatever method you're using to read this document.

What is Perl?

Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more.

The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). Its major features are that it's easy to use, supports both procedural and object-oriented (OO) programming, has powerful built-in support for text processing, and has one of the world's most impressive collections of third-party modules.

Different definitions of Perl are given in the perl manpage, the perlfaq1 manpage and no doubt other places. From this we can determine that Perl is different things to different people, but that lots of people think it's at least worth writing about.

Running Perl programs

To run a Perl program from the Unix command line:

    perl progname.pl

Alternatively, put this as the first line of your script:

    #!/usr/bin/env perl

... and run the script as /path/to/script.pl. Of course, it'll need to be executable first, so chmod 755 script.pl (under Unix).

(This start line assumes you have the env program. You can also put directly the path to your perl executable, like in #!/usr/bin/perl).

For more information, including instructions for other platforms such as Windows and Mac OS, read the perlrun manpage.

Safety net

Perl by default is very forgiving. In order to make it more robust it is recommended to start every program with the following lines:

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

The two additional lines request from perl to catch various common problems in your code. They check different things so you need both. A potential problem caught by use strict; will cause your code to stop immediately when it is encountered, while use warnings; will merely give a warning (like the command-line switch -w) and let your code run. To read more about them check their respective manual pages at the strict manpage and the warnings manpage.

Basic syntax overview

A Perl script or program consists of one or more statements. These statements are simply written in the script in a straightforward fashion. There is no need to have a main() function or anything of that kind.

Perl statements end in a semi-colon:

    print "Hello, world";

Comments start with a hash symbol and run to the end of the line

    # This is a comment

Whitespace is irrelevant:

    print
        "Hello, world"
        ;

... except inside quoted strings:

    # this would print with a linebreak in the middle
    print "Hello
    world";

Double quotes or single quotes may be used around literal strings:

    print "Hello, world";
    print 'Hello, world';

However, only double quotes "interpolate" variables and special characters such as newlines (\n):

    print "Hello, $name\n";     # works fine
    print 'Hello, $name\n';     # prints $name\n literally

Numbers don't need quotes around them:

    print 42;

You can use parentheses for functions' arguments or omit them according to your personal taste. They are only required occasionally to clarify issues of precedence.

    print("Hello, world\n");
    print "Hello, world\n";

More detailed information about Perl syntax can be found in the perlsyn manpage.

Perl variable types

Perl has three main variable types: scalars, arrays, and hashes.

Scalars

A scalar represents a single value:

    my $animal = "camel";
    my $answer = 42;

Scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required. There is no need to pre-declare your variable types, but you have to declare them using the my keyword the first time you use them. (This is one of the requirements of use strict;.)

Scalar values can be used in various ways:

    print $animal;
    print "The animal is $animal\n";
    print "The square of $answer is ", $answer * $answer, "\n";

There are a number of "magic" scalars with names that look like punctuation or line noise. These special variables are used for all kinds of purposes, and are documented in the perlvar manpage. The only one you need to know about for now is $_ which is the "default variable". It's used as the default argument to a number of functions in Perl, and it's set implicitly by certain looping constructs.

    print;          # prints contents of $_ by default
Arrays

An array represents a list of values:

    my @animals = ("camel", "llama", "owl");
    my @numbers = (23, 42, 69);
    my @mixed   = ("camel", 42, 1.23);

Arrays are zero-indexed. Here's how you get at elements in an array:

    print $animals[0];              # prints "camel"
    print $animals[1];              # prints "llama"

The special variable $#array tells you the index of the last element of an array:

    print $mixed[$#mixed];       # last element, prints 1.23

You might be tempted to use $#array + 1 to tell you how many items there are in an array. Don't bother. As it happens, using @array where Perl expects to find a scalar value ("in scalar context") will give you the number of elements in the array:

    if (@animals < 5) { ... }

The elements we're getting from the array start with a $ because we're getting just a single value out of the array -- you ask for a scalar, you get a scalar.

To get multiple values from an array:

    @animals[0,1];                  # gives ("camel", "llama");
    @animals[0..2];                 # gives ("camel", "llama", "owl");
    @animals[1..$#animals];         # gives all except the first element

This is called an "array slice".

You can do various useful things to lists:

    my @sorted    = sort @animals;
    my @backwards = reverse @numbers;

There are a couple of special arrays too, such as @ARGV (the command line arguments to your script) and @_ (the arguments passed to a subroutine). These are documented in the perlvar manpage.

Hashes

A hash represents a set of key/value pairs:

    my %fruit_color = ("apple", "red", "banana", "yellow");

You can use whitespace and the => operator to lay them out more nicely:

    my %fruit_color = (
        apple  => "red",
        banana => "yellow",
    );

To get at hash elements:

    $fruit_color{"apple"};           # gives "red"

You can get at lists of keys and values with keys() and values().

    my @fruits = keys %fruit_colors;
    my @colors = values %fruit_colors;

Hashes have no particular internal order, though you can sort the keys and loop through them.

Just like special scalars and arrays, there are also special hashes. The most well known of these is %ENV which contains environment variables. Read all about it (and other special variables) in the perlvar manpage.

Scalars, arrays and hashes are documented more fully in the perldata manpage.

More complex data types can be constructed using references, which allow you to build lists and hashes within lists and hashes.

A reference is a scalar value and can refer to any other Perl data type. So by storing a reference as the value of an array or hash element, you can easily create lists and hashes within lists and hashes. The following example shows a 2 level hash of hash structure using anonymous hash references.

    my $variables = {
        scalar  =>  {
                     description => "single item",
                     sigil => '$',
                    },
        array   =>  {
                     description => "ordered list of items",
                     sigil => '@',
                    },
        hash    =>  {
                     description => "key/value pairs",
                     sigil => '%',
                    },
    };
    print "Scalars begin with a $variables->{'scalar'}->{'sigil'}\n";

Exhaustive information on the topic of references can be found in the perlreftut manpage, the perllol manpage, the perlref manpage and the perldsc manpage.

Variable scoping

Throughout the previous section all the examples have used the syntax:

    my $var = "value";

The my is actually not required; you could just use:

    $var = "value";

However, the above usage will create global variables throughout your program, which is bad programming practice. my creates lexically scoped variables instead. The variables are scoped to the block (i.e. a bunch of statements surrounded by curly-braces) in which they are defined.

    my $x = "foo";
    my $some_condition = 1;
    if ($some_condition) {
        my $y = "bar";
        print $x;           # prints "foo"
        print $y;           # prints "bar"
    }
    print $x;               # prints "foo"
    print $y;               # prints nothing; $y has fallen out of scope

Using my in combination with a use strict; at the top of your Perl scripts means that the interpreter will pick up certain common programming errors. For instance, in the example above, the final print $b would cause a compile-time error and prevent you from running the program. Using strict is highly recommended.

Conditional and looping constructs

Perl has most of the usual conditional and looping constructs except for case/switch (but if you really want it, there is a Switch module in Perl 5.8 and newer, and on CPAN. See the section on modules, below, for more information about modules and CPAN).

The conditions can be any Perl expression. See the list of operators in the next section for information on comparison and boolean logic operators, which are commonly used in conditional statements.

if
    if ( condition ) {
        ...
    } elsif ( other condition ) {
        ...
    } else {
        ...
    }

There's also a negated version of it:

    unless ( condition ) {
        ...
    }

This is provided as a more readable version of if (!condition).

Note that the braces are required in Perl, even if you've only got one line in the block. However, there is a clever way of making your one-line conditional blocks more English like:

    # the traditional way
    if ($zippy) {
        print "Yow!";
    }
    # the Perlish post-condition way
    print "Yow!" if $zippy;
    print "We have no bananas" unless $bananas;
while
    while ( condition ) {
        ...
    }

There's also a negated version, for the same reason we have unless:

    until ( condition ) {
        ...
    }

You can also use while in a post-condition:

    print "LA LA LA\n" while 1;          # loops forever
for

Exactly like C:

    for ($i = 0; $i <= $max; $i++) {
        ...
    }

The C style for loop is rarely needed in Perl since Perl provides the more friendly list scanning foreach loop.

foreach
    foreach (@array) {
        print "This element is $_\n";
    }
    print $list[$_] foreach 0 .. $max;
    # you don't have to use the default $_ either...
    foreach my $key