3 perlintro -- a brief introduction and overview of Perl
7 This document is intended to give you a quick overview of the Perl
8 programming language, along with pointers to further documentation. It
9 is intended as a "bootstrap" guide for those who are new to the
10 language, and provides just enough information for you to be able to
11 read other peoples' Perl and understand roughly what it's doing, or
12 write your own simple scripts.
14 This introductory document does not aim to be complete. It does not
15 even aim to be entirely accurate. In some cases perfection has been
16 sacrificed in the goal of getting the general idea across. You are
17 I<strongly> advised to follow this introduction with more information
18 from the full Perl manual, the table of contents to which can be found
21 Throughout this document you'll see references to other parts of the
22 Perl documentation. You can read that documentation using the C<perldoc>
23 command or whatever method you're using to read this document.
27 Perl is a general-purpose programming language originally developed for
28 text manipulation and now used for a wide range of tasks including
29 system administration, web development, network programming, GUI
30 development, and more.
32 The language is intended to be practical (easy to use, efficient,
33 complete) rather than beautiful (tiny, elegant, minimal). Its major
34 features are that it's easy to use, supports both procedural and
35 object-oriented (OO) programming, has powerful built-in support for text
36 processing, and has one of the world's most impressive collections of
39 Different definitions of Perl are given in L<perl>, L<perlfaq1> and
40 no doubt other places. From this we can determine that Perl is different
41 things to different people, but that lots of people think it's at least
44 =head2 Running Perl programs
46 To run a Perl program from the Unix command line:
50 Alternatively, put this as the first line of your script:
54 ... and run the script as C</path/to/script.pl>. Of course, it'll need
55 to be executable first, so C<chmod 755 script.pl> (under Unix).
57 (This start line assumes you have the B<env> program. You can also put
58 directly the path to your perl executable, like in C<#!/usr/bin/perl>).
60 For more information, including instructions for other platforms such as
61 Windows and Mac OS, read L<perlrun>.
65 Perl by default is very forgiving. In order to make it more robust
66 it is recommended to start every program with the following lines:
72 The two additional lines request from perl to catch various common
73 problems in your code. They check different things so you need both. A
74 potential problem caught by C<use strict;> will cause your code to stop
75 immediately when it is encountered, while C<use warnings;> will merely
76 give a warning (like the command-line switch B<-w>) and let your code run.
77 To read more about them check their respective manual pages at L<strict>
80 =head2 Basic syntax overview
82 A Perl script or program consists of one or more statements. These
83 statements are simply written in the script in a straightforward
84 fashion. There is no need to have a C<main()> function or anything of
87 Perl statements end in a semi-colon:
91 Comments start with a hash symbol and run to the end of the line
95 Whitespace is irrelevant:
101 ... except inside quoted strings:
103 # this would print with a linebreak in the middle
107 Double quotes or single quotes may be used around literal strings:
109 print "Hello, world";
110 print 'Hello, world';
112 However, only double quotes "interpolate" variables and special
113 characters such as newlines (C<\n>):
115 print "Hello, $name\n"; # works fine
116 print 'Hello, $name\n'; # prints $name\n literally
118 Numbers don't need quotes around them:
122 You can use parentheses for functions' arguments or omit them
123 according to your personal taste. They are only required
124 occasionally to clarify issues of precedence.
126 print("Hello, world\n");
127 print "Hello, world\n";
129 More detailed information about Perl syntax can be found in L<perlsyn>.
131 =head2 Perl variable types
133 Perl has three main variable types: scalars, arrays, and hashes.
139 A scalar represents a single value:
141 my $animal = "camel";
144 Scalar values can be strings, integers or floating point numbers, and Perl
145 will automatically convert between them as required. There is no need
146 to pre-declare your variable types, but you have to declare them using
147 the C<my> keyword the first time you use them. (This is one of the
148 requirements of C<use strict;>.)
150 Scalar values can be used in various ways:
153 print "The animal is $animal\n";
154 print "The square of $answer is ", $answer * $answer, "\n";
156 There are a number of "magic" scalars with names that look like
157 punctuation or line noise. These special variables are used for all
158 kinds of purposes, and are documented in L<perlvar>. The only one you
159 need to know about for now is C<$_> which is the "default variable".
160 It's used as the default argument to a number of functions in Perl, and
161 it's set implicitly by certain looping constructs.
163 print; # prints contents of $_ by default
167 An array represents a list of values:
169 my @animals = ("camel", "llama", "owl");
170 my @numbers = (23, 42, 69);
171 my @mixed = ("camel", 42, 1.23);
173 Arrays are zero-indexed. Here's how you get at elements in an array:
175 print $animals[0]; # prints "camel"
176 print $animals[1]; # prints "llama"
178 The special variable C<$#array> tells you the index of the last element
181 print $mixed[$#mixed]; # last element, prints 1.23
183 You might be tempted to use C<$#array + 1> to tell you how many items there
184 are in an array. Don't bother. As it happens, using C<@array> where Perl
185 expects to find a scalar value ("in scalar context") will give you the number
186 of elements in the array:
188 if (@animals < 5) { ... }
190 The elements we're getting from the array start with a C<$> because
191 we're getting just a single value out of the array; you ask for a scalar,
194 To get multiple values from an array:
196 @animals[0,1]; # gives ("camel", "llama");
197 @animals[0..2]; # gives ("camel", "llama", "owl");
198 @animals[1..$#animals]; # gives all except the first element
200 This is called an "array slice".
202 You can do various useful things to lists:
204 my @sorted = sort @animals;
205 my @backwards = reverse @numbers;
207 There are a couple of special arrays too, such as C<@ARGV> (the command
208 line arguments to your script) and C<@_> (the arguments passed to a
209 subroutine). These are documented in L<perlvar>.
213 A hash represents a set of key/value pairs:
215 my %fruit_color = ("apple", "red", "banana", "yellow");
217 You can use whitespace and the C<< => >> operator to lay them out more
225 To get at hash elements:
227 $fruit_color{"apple"}; # gives "red"
229 You can get at lists of keys and values with C<keys()> and
232 my @fruits = keys %fruit_colors;
233 my @colors = values %fruit_colors;
235 Hashes have no particular internal order, though you can sort the keys
236 and loop through them.
238 Just like special scalars and arrays, there are also special hashes.
239 The most well known of these is C<%ENV> which contains environment
240 variables. Read all about it (and other special variables) in
245 Scalars, arrays and hashes are documented more fully in L<perldata>.
247 More complex data types can be constructed using references, which allow
248 you to build lists and hashes within lists and hashes.
250 A reference is a scalar value and can refer to any other Perl data
251 type. So by storing a reference as the value of an array or hash
252 element, you can easily create lists and hashes within lists and
253 hashes. The following example shows a 2 level hash of hash
254 structure using anonymous hash references.
258 description => "single item",
262 description => "ordered list of items",
266 description => "key/value pairs",
271 print "Scalars begin with a $variables->{'scalar'}->{'sigil'}\n";
273 Exhaustive information on the topic of references can be found in
274 L<perlreftut>, L<perllol>, L<perlref> and L<perldsc>.
276 =head2 Variable scoping
278 Throughout the previous section all the examples have used the syntax:
282 The C<my> is actually not required; you could just use:
286 However, the above usage will create global variables throughout your
287 program, which is bad programming practice. C<my> creates lexically
288 scoped variables instead. The variables are scoped to the block
289 (i.e. a bunch of statements surrounded by curly-braces) in which they
293 my $some_condition = 1;
294 if ($some_condition) {
296 print $x; # prints "foo"
297 print $y; # prints "bar"
299 print $x; # prints "foo"
300 print $y; # prints nothing; $y has fallen out of scope
302 Using C<my> in combination with a C<use strict;> at the top of
303 your Perl scripts means that the interpreter will pick up certain common
304 programming errors. For instance, in the example above, the final
305 C<print $y> would cause a compile-time error and prevent you from
306 running the program. Using C<strict> is highly recommended.
308 =head2 Conditional and looping constructs
310 Perl has most of the usual conditional and looping constructs. As of Perl
311 5.10, it even has a case/switch statement (spelled C<given>/C<when>). See
312 L<perlsyn/"Switch statements"> for more details.
314 The conditions can be any Perl expression. See the list of operators in
315 the next section for information on comparison and boolean logic operators,
316 which are commonly used in conditional statements.
324 } elsif ( other condition ) {
330 There's also a negated version of it:
332 unless ( condition ) {
336 This is provided as a more readable version of C<if (!I<condition>)>.
338 Note that the braces are required in Perl, even if you've only got one
339 line in the block. However, there is a clever way of making your one-line
340 conditional blocks more English like:
342 # the traditional way
347 # the Perlish post-condition way
348 print "Yow!" if $zippy;
349 print "We have no bananas" unless $bananas;
353 while ( condition ) {
357 There's also a negated version, for the same reason we have C<unless>:
359 until ( condition ) {
363 You can also use C<while> in a post-condition:
365 print "LA LA LA\n" while 1; # loops forever
371 for ($i = 0; $i <= $max; $i++) {
375 The C style for loop is rarely needed in Perl since Perl provides
376 the more friendly list scanning C<foreach> loop.
381 print "This element is $_\n";
384 print $list[$_] foreach 0 .. $max;
386 # you don't have to use the default $_ either...
387 foreach my $key (keys %hash) {
388 print "The value of $key is $hash{$key}\n";
393 For more detail on looping constructs (and some that weren't mentioned in
394 this overview) see L<perlsyn>.
396 =head2 Builtin operators and functions
398 Perl comes with a wide selection of builtin functions. Some of the ones
399 we've already seen include C<print>, C<sort> and C<reverse>. A list of
400 them is given at the start of L<perlfunc> and you can easily read
401 about any given function by using C<perldoc -f I<functionname>>.
403 Perl operators are documented in full in L<perlop>, but here are a few
404 of the most common ones:
415 =item Numeric comparison
421 <= less than or equal
422 >= greater than or equal
424 =item String comparison
430 le less than or equal
431 ge greater than or equal
433 (Why do we have separate numeric and string comparisons? Because we don't
434 have special variable types, and Perl needs to know whether to sort
435 numerically (where 99 is less than 100) or alphabetically (where 100 comes
444 (C<and>, C<or> and C<not> aren't just in the above table as descriptions
445 of the operators. They're also supported as operators in their own
446 right. They're more readable than the C-style operators, but have
447 different precedence to C<&&> and friends. Check L<perlop> for more
453 . string concatenation
454 x string multiplication
455 .. range operator (creates a list of numbers)
459 Many operators can be combined with a C<=> as follows:
461 $a += 1; # same as $a = $a + 1
462 $a -= 1; # same as $a = $a - 1
463 $a .= "\n"; # same as $a = $a . "\n";
467 You can open a file for input or output using the C<open()> function.
468 It's documented in extravagant detail in L<perlfunc> and L<perlopentut>,
471 open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
472 open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
473 open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
475 You can read from an open filehandle using the C<< <> >> operator. In
476 scalar context it reads a single line from the filehandle, and in list
477 context it reads the whole file in, assigning each line to an element of
483 Reading in the whole file at one time is called slurping. It can
484 be useful but it may be a memory hog. Most text file processing
485 can be done a line at a time with Perl's looping constructs.
487 The C<< <> >> operator is most often seen in a C<while> loop:
489 while (<$in>) { # assigns each line in turn to $_
490 print "Just read in this line: $_";
493 We've already seen how to print to standard output using C<print()>.
494 However, C<print()> can also take an optional first argument specifying
495 which filehandle to print to:
497 print STDERR "This is your final warning.\n";
499 print $log $logmessage;
501 When you're done with your filehandles, you should C<close()> them
502 (though to be honest, Perl will clean up after you if you forget):
504 close $in or die "$in: $!";
506 =head2 Regular expressions
508 Perl's regular expression support is both broad and deep, and is the
509 subject of lengthy documentation in L<perlrequick>, L<perlretut>, and
510 elsewhere. However, in short:
514 =item Simple matching
516 if (/foo/) { ... } # true if $_ contains "foo"
517 if ($a =~ /foo/) { ... } # true if $a contains "foo"
519 The C<//> matching operator is documented in L<perlop>. It operates on
520 C<$_> by default, or can be bound to another variable using the C<=~>
521 binding operator (also documented in L<perlop>).
523 =item Simple substitution
525 s/foo/bar/; # replaces foo with bar in $_
526 $a =~ s/foo/bar/; # replaces foo with bar in $a
527 $a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $a
529 The C<s///> substitution operator is documented in L<perlop>.
531 =item More complex regular expressions
533 You don't just have to match on fixed strings. In fact, you can match
534 on just about anything you could dream of by using more complex regular
535 expressions. These are documented at great length in L<perlre>, but for
536 the meantime, here's a quick cheat sheet:
539 \s a whitespace character (space, tab, newline, ...)
540 \S non-whitespace character
543 \w a word character (a-z, A-Z, 0-9, _)
544 \W a non-word character
545 [aeiou] matches a single character in the given set
546 [^aeiou] matches a single character outside the given set
547 (foo|bar|baz) matches any of the alternatives specified
552 Quantifiers can be used to specify how many of the previous thing you
553 want to match on, where "thing" means either a literal character, one
554 of the metacharacters listed above, or a group of characters or
555 metacharacters in parentheses.
557 * zero or more of the previous thing
558 + one or more of the previous thing
559 ? zero or one of the previous thing
560 {3} matches exactly 3 of the previous thing
561 {3,6} matches between 3 and 6 of the previous thing
562 {3,} matches 3 or more of the previous thing
566 /^\d+/ string starts with one or more digits
567 /^$/ nothing in the string (start and end are adjacent)
568 /(\d\s){3}/ a three digits, each followed by a whitespace
569 character (eg "3 4 5 ")
570 /(a.)+/ matches a string in which every odd-numbered letter
573 # This loop reads from STDIN, and prints non-blank lines:
579 =item Parentheses for capturing
581 As well as grouping, parentheses serve a second purpose. They can be
582 used to capture the results of parts of the regexp match for later use.
583 The results end up in C<$1>, C<$2> and so on.
585 # a cheap and nasty way to break an email address up into parts
587 if ($email =~ /([^@]+)@(.+)/) {
588 print "Username is $1\n";
589 print "Hostname is $2\n";
592 =item Other regexp features
594 Perl regexps also support backreferences, lookaheads, and all kinds of
595 other complex details. Read all about them in L<perlrequick>,
596 L<perlretut>, and L<perlre>.
600 =head2 Writing subroutines
602 Writing subroutines is easy:
605 my $logmessage = shift;
606 open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
607 print $logfile $logmessage;
610 Now we can use the subroutine just as any other built-in function:
612 logger("We have a logger subroutine!");
614 What's that C<shift>? Well, the arguments to a subroutine are available
615 to us as a special array called C<@_> (see L<perlvar> for more on that).
616 The default argument to the C<shift> function just happens to be C<@_>.
617 So C<my $logmessage = shift;> shifts the first item off the list of
618 arguments and assigns it to C<$logmessage>.
620 We can manipulate C<@_> in other ways too:
622 my ($logmessage, $priority) = @_; # common
623 my $logmessage = $_[0]; # uncommon, and ugly
625 Subroutines can also return values:
629 my $result = $num * $num;
637 For more information on writing subroutines, see L<perlsub>.
641 OO Perl is relatively simple and is implemented using references which
642 know what sort of object they are based on Perl's concept of packages.
643 However, OO Perl is largely beyond the scope of this document.
644 Read L<perlboot>, L<perltoot>, L<perltooc> and L<perlobj>.
646 As a beginning Perl programmer, your most common use of OO Perl will be
647 in using third-party modules, which are documented below.
649 =head2 Using Perl modules
651 Perl modules provide a range of features to help you avoid reinventing
652 the wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). A
653 number of popular modules are included with the Perl distribution
656 Categories of modules range from text manipulation to network protocols
657 to database integration to graphics. A categorized list of modules is
658 also available from CPAN.
660 To learn how to install modules you download from CPAN, read
663 To learn how to use a particular module, use C<perldoc I<Module::Name>>.
664 Typically you will want to C<use I<Module::Name>>, which will then give
665 you access to exported functions or an OO interface to the module.
667 L<perlfaq> contains questions and answers related to many common
668 tasks, and often provides suggestions for good CPAN modules to use.
670 L<perlmod> describes Perl modules in general. L<perlmodlib> lists the
671 modules which came with your Perl installation.
673 If you feel the urge to write Perl modules, L<perlnewmod> will give you
678 Kirrily "Skud" Robert <skud@cpan.org>