1N/A=head1 NAME
1N/A
1N/Aperlintro -- a brief introduction and overview of Perl
1N/A
1N/A=head1 DESCRIPTION
1N/A
1N/AThis document is intended to give you a quick overview of the Perl
1N/Aprogramming language, along with pointers to further documentation. It
1N/Ais intended as a "bootstrap" guide for those who are new to the
1N/Alanguage, and provides just enough information for you to be able to
1N/Aread other peoples' Perl and understand roughly what it's doing, or
1N/Awrite your own simple scripts.
1N/A
1N/AThis introductory document does not aim to be complete. It does not
1N/Aeven aim to be entirely accurate. In some cases perfection has been
1N/Asacrificed in the goal of getting the general idea across. You are
1N/AI<strongly> advised to follow this introduction with more information
1N/Afrom the full Perl manual, the table of contents to which can be found
1N/Ain L<perltoc>.
1N/A
1N/AThroughout this document you'll see references to other parts of the
1N/APerl documentation. You can read that documentation using the C<perldoc>
1N/Acommand or whatever method you're using to read this document.
1N/A
1N/A=head2 What is Perl?
1N/A
1N/APerl is a general-purpose programming language originally developed for
1N/Atext manipulation and now used for a wide range of tasks including
1N/Asystem administration, web development, network programming, GUI
1N/Adevelopment, and more.
1N/A
1N/AThe language is intended to be practical (easy to use, efficient,
1N/Acomplete) rather than beautiful (tiny, elegant, minimal). Its major
1N/Afeatures are that it's easy to use, supports both procedural and
1N/Aobject-oriented (OO) programming, has powerful built-in support for text
1N/Aprocessing, and has one of the world's most impressive collections of
1N/Athird-party modules.
1N/A
1N/ADifferent definitions of Perl are given in L<perl>, L<perlfaq1> and
1N/Ano doubt other places. From this we can determine that Perl is different
1N/Athings to different people, but that lots of people think it's at least
1N/Aworth writing about.
1N/A
1N/A=head2 Running Perl programs
1N/A
1N/ATo run a Perl program from the Unix command line:
1N/A
1N/A perl progname.pl
1N/A
1N/AAlternatively, put this as the first line of your script:
1N/A
1N/A #!/usr/bin/env perl
1N/A
1N/A... and run the script as C</path/to/script.pl>. Of course, it'll need
1N/Ato be executable first, so C<chmod 755 script.pl> (under Unix).
1N/A
1N/AFor more information, including instructions for other platforms such as
1N/AWindows and Mac OS, read L<perlrun>.
1N/A
1N/A=head2 Basic syntax overview
1N/A
1N/AA Perl script or program consists of one or more statements. These
1N/Astatements are simply written in the script in a straightforward
1N/Afashion. There is no need to have a C<main()> function or anything of
1N/Athat kind.
1N/A
1N/APerl statements end in a semi-colon:
1N/A
1N/A print "Hello, world";
1N/A
1N/AComments start with a hash symbol and run to the end of the line
1N/A
1N/A # This is a comment
1N/A
1N/AWhitespace is irrelevant:
1N/A
1N/A print
1N/A "Hello, world"
1N/A ;
1N/A
1N/A... except inside quoted strings:
1N/A
1N/A # this would print with a linebreak in the middle
1N/A print "Hello
1N/A world";
1N/A
1N/ADouble quotes or single quotes may be used around literal strings:
1N/A
1N/A print "Hello, world";
1N/A print 'Hello, world';
1N/A
1N/AHowever, only double quotes "interpolate" variables and special
1N/Acharacters such as newlines (C<\n>):
1N/A
1N/A print "Hello, $name\n"; # works fine
1N/A print 'Hello, $name\n'; # prints $name\n literally
1N/A
1N/ANumbers don't need quotes around them:
1N/A
1N/A print 42;
1N/A
1N/AYou can use parentheses for functions' arguments or omit them
1N/Aaccording to your personal taste. They are only required
1N/Aoccasionally to clarify issues of precedence.
1N/A
1N/A print("Hello, world\n");
1N/A print "Hello, world\n";
1N/A
1N/AMore detailed information about Perl syntax can be found in L<perlsyn>.
1N/A
1N/A=head2 Perl variable types
1N/A
1N/APerl has three main variable types: scalars, arrays, and hashes.
1N/A
1N/A=over 4
1N/A
1N/A=item Scalars
1N/A
1N/AA scalar represents a single value:
1N/A
1N/A my $animal = "camel";
1N/A my $answer = 42;
1N/A
1N/AScalar values can be strings, integers or floating point numbers, and Perl
1N/Awill automatically convert between them as required. There is no need
1N/Ato pre-declare your variable types.
1N/A
1N/AScalar values can be used in various ways:
1N/A
1N/A print $animal;
1N/A print "The animal is $animal\n";
1N/A print "The square of $answer is ", $answer * $answer, "\n";
1N/A
1N/AThere are a number of "magic" scalars with names that look like
1N/Apunctuation or line noise. These special variables are used for all
1N/Akinds of purposes, and are documented in L<perlvar>. The only one you
1N/Aneed to know about for now is C<$_> which is the "default variable".
1N/AIt's used as the default argument to a number of functions in Perl, and
1N/Ait's set implicitly by certain looping constructs.
1N/A
1N/A print; # prints contents of $_ by default
1N/A
1N/A=item Arrays
1N/A
1N/AAn array represents a list of values:
1N/A
1N/A my @animals = ("camel", "llama", "owl");
1N/A my @numbers = (23, 42, 69);
1N/A my @mixed = ("camel", 42, 1.23);
1N/A
1N/AArrays are zero-indexed. Here's how you get at elements in an array:
1N/A
1N/A print $animals[0]; # prints "camel"
1N/A print $animals[1]; # prints "llama"
1N/A
1N/AThe special variable C<$#array> tells you the index of the last element
1N/Aof an array:
1N/A
1N/A print $mixed[$#mixed]; # last element, prints 1.23
1N/A
1N/AYou might be tempted to use C<$#array + 1> to tell you how many items there
1N/Aare in an array. Don't bother. As it happens, using C<@array> where Perl
1N/Aexpects to find a scalar value ("in scalar context") will give you the number
1N/Aof elements in the array:
1N/A
1N/A if (@animals < 5) { ... }
1N/A
1N/AThe elements we're getting from the array start with a C<$> because
1N/Awe're getting just a single value out of the array -- you ask for a scalar,
1N/Ayou get a scalar.
1N/A
1N/ATo get multiple values from an array:
1N/A
1N/A @animals[0,1]; # gives ("camel", "llama");
1N/A @animals[0..2]; # gives ("camel", "llama", "owl");
1N/A @animals[1..$#animals]; # gives all except the first element
1N/A
1N/AThis is called an "array slice".
1N/A
1N/AYou can do various useful things to lists:
1N/A
1N/A my @sorted = sort @animals;
1N/A my @backwards = reverse @numbers;
1N/A
1N/AThere are a couple of special arrays too, such as C<@ARGV> (the command
1N/Aline arguments to your script) and C<@_> (the arguments passed to a
1N/Asubroutine). These are documented in L<perlvar>.
1N/A
1N/A=item Hashes
1N/A
1N/AA hash represents a set of key/value pairs:
1N/A
1N/A my %fruit_color = ("apple", "red", "banana", "yellow");
1N/A
1N/AYou can use whitespace and the C<< => >> operator to lay them out more
1N/Anicely:
1N/A
1N/A my %fruit_color = (
1N/A apple => "red",
1N/A banana => "yellow",
1N/A );
1N/A
1N/ATo get at hash elements:
1N/A
1N/A $fruit_color{"apple"}; # gives "red"
1N/A
1N/AYou can get at lists of keys and values with C<keys()> and
1N/AC<values()>.
1N/A
1N/A my @fruits = keys %fruit_colors;
1N/A my @colors = values %fruit_colors;
1N/A
1N/AHashes have no particular internal order, though you can sort the keys
1N/Aand loop through them.
1N/A
1N/AJust like special scalars and arrays, there are also special hashes.
1N/AThe most well known of these is C<%ENV> which contains environment
1N/Avariables. Read all about it (and other special variables) in
1N/AL<perlvar>.
1N/A
1N/A=back
1N/A
1N/AScalars, arrays and hashes are documented more fully in L<perldata>.
1N/A
1N/AMore complex data types can be constructed using references, which allow
1N/Ayou to build lists and hashes within lists and hashes.
1N/A
1N/AA reference is a scalar value and can refer to any other Perl data
1N/Atype. So by storing a reference as the value of an array or hash
1N/Aelement, you can easily create lists and hashes within lists and
1N/Ahashes. The following example shows a 2 level hash of hash
1N/Astructure using anonymous hash references.
1N/A
1N/A my $variables = {
1N/A scalar => {
1N/A description => "single item",
1N/A sigil => '$',
1N/A },
1N/A array => {
1N/A description => "ordered list of items",
1N/A sigil => '@',
1N/A },
1N/A hash => {
1N/A description => "key/value pairs",
1N/A sigil => '%',
1N/A },
1N/A };
1N/A
1N/A print "Scalars begin with a $variables->{'scalar'}->{'sigil'}\n";
1N/A
1N/AExhaustive information on the topic of references can be found in
1N/AL<perlreftut>, L<perllol>, L<perlref> and L<perldsc>.
1N/A
1N/A=head2 Variable scoping
1N/A
1N/AThroughout the previous section all the examples have used the syntax:
1N/A
1N/A my $var = "value";
1N/A
1N/AThe C<my> is actually not required; you could just use:
1N/A
1N/A $var = "value";
1N/A
1N/AHowever, the above usage will create global variables throughout your
1N/Aprogram, which is bad programming practice. C<my> creates lexically
1N/Ascoped variables instead. The variables are scoped to the block
1N/A(i.e. a bunch of statements surrounded by curly-braces) in which they
1N/Aare defined.
1N/A
1N/A my $a = "foo";
1N/A if ($some_condition) {
1N/A my $b = "bar";
1N/A print $a; # prints "foo"
1N/A print $b; # prints "bar"
1N/A }
1N/A print $a; # prints "foo"
1N/A print $b; # prints nothing; $b has fallen out of scope
1N/A
1N/AUsing C<my> in combination with a C<use strict;> at the top of
1N/Ayour Perl scripts means that the interpreter will pick up certain common
1N/Aprogramming errors. For instance, in the example above, the final
1N/AC<print $b> would cause a compile-time error and prevent you from
1N/Arunning the program. Using C<strict> is highly recommended.
1N/A
1N/A=head2 Conditional and looping constructs
1N/A
1N/APerl has most of the usual conditional and looping constructs except for
1N/Acase/switch (but if you really want it, there is a Switch module in Perl
1N/A5.8 and newer, and on CPAN. See the section on modules, below, for more
1N/Ainformation about modules and CPAN).
1N/A
1N/AThe conditions can be any Perl expression. See the list of operators in
1N/Athe next section for information on comparison and boolean logic operators,
1N/Awhich are commonly used in conditional statements.
1N/A
1N/A=over 4
1N/A
1N/A=item if
1N/A
1N/A if ( condition ) {
1N/A ...
1N/A } elsif ( other condition ) {
1N/A ...
1N/A } else {
1N/A ...
1N/A }
1N/A
1N/AThere's also a negated version of it:
1N/A
1N/A unless ( condition ) {
1N/A ...
1N/A }
1N/A
1N/AThis is provided as a more readable version of C<if (!I<condition>)>.
1N/A
1N/ANote that the braces are required in Perl, even if you've only got one
1N/Aline in the block. However, there is a clever way of making your one-line
1N/Aconditional blocks more English like:
1N/A
1N/A # the traditional way
1N/A if ($zippy) {
1N/A print "Yow!";
1N/A }
1N/A
1N/A # the Perlish post-condition way
1N/A print "Yow!" if $zippy;
1N/A print "We have no bananas" unless $bananas;
1N/A
1N/A=item while
1N/A
1N/A while ( condition ) {
1N/A ...
1N/A }
1N/A
1N/AThere's also a negated version, for the same reason we have C<unless>:
1N/A
1N/A until ( condition ) {
1N/A ...
1N/A }
1N/A
1N/AYou can also use C<while> in a post-condition:
1N/A
1N/A print "LA LA LA\n" while 1; # loops forever
1N/A
1N/A=item for
1N/A
1N/AExactly like C:
1N/A
1N/A for ($i=0; $i <= $max; $i++) {
1N/A ...
1N/A }
1N/A
1N/AThe C style for loop is rarely needed in Perl since Perl provides
1N/Athe more friendly list scanning C<foreach> loop.
1N/A
1N/A=item foreach
1N/A
1N/A foreach (@array) {
1N/A print "This element is $_\n";
1N/A }
1N/A
1N/A # you don't have to use the default $_ either...
1N/A foreach my $key (keys %hash) {
1N/A print "The value of $key is $hash{$key}\n";
1N/A }
1N/A
1N/A=back
1N/A
1N/AFor more detail on looping constructs (and some that weren't mentioned in
1N/Athis overview) see L<perlsyn>.
1N/A
1N/A=head2 Builtin operators and functions
1N/A
1N/APerl comes with a wide selection of builtin functions. Some of the ones
1N/Awe've already seen include C<print>, C<sort> and C<reverse>. A list of
1N/Athem is given at the start of L<perlfunc> and you can easily read
1N/Aabout any given function by using C<perldoc -f I<functionname>>.
1N/A
1N/APerl operators are documented in full in L<perlop>, but here are a few
1N/Aof the most common ones:
1N/A
1N/A=over 4
1N/A
1N/A=item Arithmetic
1N/A
1N/A + addition
1N/A - subtraction
1N/A * multiplication
1N/A / division
1N/A
1N/A=item Numeric comparison
1N/A
1N/A == equality
1N/A != inequality
1N/A < less than
1N/A > greater than
1N/A <= less than or equal
1N/A >= greater than or equal
1N/A
1N/A=item String comparison
1N/A
1N/A eq equality
1N/A ne inequality
1N/A lt less than
1N/A gt greater than
1N/A le less than or equal
1N/A ge greater than or equal
1N/A
1N/A(Why do we have separate numeric and string comparisons? Because we don't
1N/Ahave special variable types, and Perl needs to know whether to sort
1N/Anumerically (where 99 is less than 100) or alphabetically (where 100 comes
1N/Abefore 99).
1N/A
1N/A=item Boolean logic
1N/A
1N/A && and
1N/A || or
1N/A ! not
1N/A
1N/A(C<and>, C<or> and C<not> aren't just in the above table as descriptions
1N/Aof the operators -- they're also supported as operators in their own
1N/Aright. They're more readable than the C-style operators, but have
1N/Adifferent precedence to C<&&> and friends. Check L<perlop> for more
1N/Adetail.)
1N/A
1N/A=item Miscellaneous
1N/A
1N/A = assignment
1N/A . string concatenation
1N/A x string multiplication
1N/A .. range operator (creates a list of numbers)
1N/A
1N/A=back
1N/A
1N/AMany operators can be combined with a C<=> as follows:
1N/A
1N/A $a += 1; # same as $a = $a + 1
1N/A $a -= 1; # same as $a = $a - 1
1N/A $a .= "\n"; # same as $a = $a . "\n";
1N/A
1N/A=head2 Files and I/O
1N/A
1N/AYou can open a file for input or output using the C<open()> function.
1N/AIt's documented in extravagant detail in L<perlfunc> and L<perlopentut>,
1N/Abut in short:
1N/A
1N/A open(INFILE, "input.txt") or die "Can't open input.txt: $!";
1N/A open(OUTFILE, ">output.txt") or die "Can't open output.txt: $!";
1N/A open(LOGFILE, ">>my.log") or die "Can't open logfile: $!";
1N/A
1N/AYou can read from an open filehandle using the C<< <> >> operator. In
1N/Ascalar context it reads a single line from the filehandle, and in list
1N/Acontext it reads the whole file in, assigning each line to an element of
1N/Athe list:
1N/A
1N/A my $line = <INFILE>;
1N/A my @lines = <INFILE>;
1N/A
1N/AReading in the whole file at one time is called slurping. It can
1N/Abe useful but it may be a memory hog. Most text file processing
1N/Acan be done a line at a time with Perl's looping constructs.
1N/A
1N/AThe C<< <> >> operator is most often seen in a C<while> loop:
1N/A
1N/A while (<INFILE>) { # assigns each line in turn to $_
1N/A print "Just read in this line: $_";
1N/A }
1N/A
1N/AWe've already seen how to print to standard output using C<print()>.
1N/AHowever, C<print()> can also take an optional first argument specifying
1N/Awhich filehandle to print to:
1N/A
1N/A print STDERR "This is your final warning.\n";
1N/A print OUTFILE $record;
1N/A print LOGFILE $logmessage;
1N/A
1N/AWhen you're done with your filehandles, you should C<close()> them
1N/A(though to be honest, Perl will clean up after you if you forget):
1N/A
1N/A close INFILE;
1N/A
1N/A=head2 Regular expressions
1N/A
1N/APerl's regular expression support is both broad and deep, and is the
1N/Asubject of lengthy documentation in L<perlrequick>, L<perlretut>, and
1N/Aelsewhere. However, in short:
1N/A
1N/A=over 4
1N/A
1N/A=item Simple matching
1N/A
1N/A if (/foo/) { ... } # true if $_ contains "foo"
1N/A if ($a =~ /foo/) { ... } # true if $a contains "foo"
1N/A
1N/AThe C<//> matching operator is documented in L<perlop>. It operates on
1N/AC<$_> by default, or can be bound to another variable using the C<=~>
1N/Abinding operator (also documented in L<perlop>).
1N/A
1N/A=item Simple substitution
1N/A
1N/A s/foo/bar/; # replaces foo with bar in $_
1N/A $a =~ s/foo/bar/; # replaces foo with bar in $a
1N/A $a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $a
1N/A
1N/AThe C<s///> substitution operator is documented in L<perlop>.
1N/A
1N/A=item More complex regular expressions
1N/A
1N/AYou don't just have to match on fixed strings. In fact, you can match
1N/Aon just about anything you could dream of by using more complex regular
1N/Aexpressions. These are documented at great length in L<perlre>, but for
1N/Athe meantime, here's a quick cheat sheet:
1N/A
1N/A . a single character
1N/A \s a whitespace character (space, tab, newline)
1N/A \S non-whitespace character
1N/A \d a digit (0-9)
1N/A \D a non-digit
1N/A \w a word character (a-z, A-Z, 0-9, _)
1N/A \W a non-word character
1N/A [aeiou] matches a single character in the given set
1N/A [^aeiou] matches a single character outside the given set
1N/A (foo|bar|baz) matches any of the alternatives specified
1N/A
1N/A ^ start of string
1N/A $ end of string
1N/A
1N/AQuantifiers can be used to specify how many of the previous thing you
1N/Awant to match on, where "thing" means either a literal character, one
1N/Aof the metacharacters listed above, or a group of characters or
1N/Ametacharacters in parentheses.
1N/A
1N/A * zero or more of the previous thing
1N/A + one or more of the previous thing
1N/A ? zero or one of the previous thing
1N/A {3} matches exactly 3 of the previous thing
1N/A {3,6} matches between 3 and 6 of the previous thing
1N/A {3,} matches 3 or more of the previous thing
1N/A
1N/ASome brief examples:
1N/A
1N/A /^\d+/ string starts with one or more digits
1N/A /^$/ nothing in the string (start and end are adjacent)
1N/A /(\d\s){3}/ a three digits, each followed by a whitespace
1N/A character (eg "3 4 5 ")
1N/A /(a.)+/ matches a string in which every odd-numbered letter
1N/A is a (eg "abacadaf")
1N/A
1N/A # This loop reads from STDIN, and prints non-blank lines:
1N/A while (<>) {
1N/A next if /^$/;
1N/A print;
1N/A }
1N/A
1N/A=item Parentheses for capturing
1N/A
1N/AAs well as grouping, parentheses serve a second purpose. They can be
1N/Aused to capture the results of parts of the regexp match for later use.
1N/AThe results end up in C<$1>, C<$2> and so on.
1N/A
1N/A # a cheap and nasty way to break an email address up into parts
1N/A
1N/A if ($email =~ /([^@])+@(.+)/) {
1N/A print "Username is $1\n";
1N/A print "Hostname is $2\n";
1N/A }
1N/A
1N/A=item Other regexp features
1N/A
1N/APerl regexps also support backreferences, lookaheads, and all kinds of
1N/Aother complex details. Read all about them in L<perlrequick>,
1N/AL<perlretut>, and L<perlre>.
1N/A
1N/A=back
1N/A
1N/A=head2 Writing subroutines
1N/A
1N/AWriting subroutines is easy:
1N/A
1N/A sub log {
1N/A my $logmessage = shift;
1N/A print LOGFILE $logmessage;
1N/A }
1N/A
1N/AWhat's that C<shift>? Well, the arguments to a subroutine are available
1N/Ato us as a special array called C<@_> (see L<perlvar> for more on that).
1N/AThe default argument to the C<shift> function just happens to be C<@_>.
1N/ASo C<my $logmessage = shift;> shifts the first item off the list of
1N/Aarguments and assigns it to C<$logmessage>.
1N/A
1N/AWe can manipulate C<@_> in other ways too:
1N/A
1N/A my ($logmessage, $priority) = @_; # common
1N/A my $logmessage = $_[0]; # uncommon, and ugly
1N/A
1N/ASubroutines can also return values:
1N/A
1N/A sub square {
1N/A my $num = shift;
1N/A my $result = $num * $num;
1N/A return $result;
1N/A }
1N/A
1N/AFor more information on writing subroutines, see L<perlsub>.
1N/A
1N/A=head2 OO Perl
1N/A
1N/AOO Perl is relatively simple and is implemented using references which
1N/Aknow what sort of object they are based on Perl's concept of packages.
1N/AHowever, OO Perl is largely beyond the scope of this document.
1N/ARead L<perlboot>, L<perltoot>, L<perltooc> and L<perlobj>.
1N/A
1N/AAs a beginning Perl programmer, your most common use of OO Perl will be
1N/Ain using third-party modules, which are documented below.
1N/A
1N/A=head2 Using Perl modules
1N/A
1N/APerl modules provide a range of features to help you avoid reinventing
1N/Athe wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). A
1N/Anumber of popular modules are included with the Perl distribution
1N/Aitself.
1N/A
1N/ACategories of modules range from text manipulation to network protocols
1N/Ato database integration to graphics. A categorized list of modules is
1N/Aalso available from CPAN.
1N/A
1N/ATo learn how to install modules you download from CPAN, read
1N/AL<perlmodinstall>
1N/A
1N/ATo learn how to use a particular module, use C<perldoc I<Module::Name>>.
1N/ATypically you will want to C<use I<Module::Name>>, which will then give
1N/Ayou access to exported functions or an OO interface to the module.
1N/A
1N/AL<perlfaq> contains questions and answers related to many common
1N/Atasks, and often provides suggestions for good CPAN modules to use.
1N/A
1N/AL<perlmod> describes Perl modules in general. L<perlmodlib> lists the
1N/Amodules which came with your Perl installation.
1N/A
1N/AIf you feel the urge to write Perl modules, L<perlnewmod> will give you
1N/Agood advice.
1N/A
1N/A=head1 AUTHOR
1N/A
1N/AKirrily "Skud" Robert <skud@cpan.org>