Relink to use temp file forced on current dir in mpeix
[p5sagit/p5-mst-13.2.git] / pod / perlintro.pod
1 =head1 NAME
2
3 perlintro -- a brief introduction and overview of Perl
4
5 =head1 DESCRIPTION
6
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.
13
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
19 in L<perltoc>.
20
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.
24
25 =head2 What is Perl?
26
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.
31
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
37 third-party modules.
38
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
42 worth writing about.
43
44 =head2 Running Perl programs
45
46 To run a Perl program from the Unix command line:
47
48     perl progname.pl
49
50 Alternatively, put this as the first line of your script:
51
52     #!/usr/bin/env perl
53
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).
56
57 For more information, including instructions for other platforms such as
58 Windows and Mac OS, read L<perlrun>.
59
60 =head2 Safety net
61
62 Perl by default is very forgiving. In order to make it more roboust
63 it is recommened to start every program with the following lines:
64
65     #!/usr/bin/perl
66     use strict;
67     use warnings;
68
69 The C<use strict;> line imposes some restrictions that will mainly stop
70 you from introducing bugs in your code.  The C<use warnings;> is more or
71 less equivalent to the command line switch B<-w> (see L<perlrun>). This will
72 catch various problems in your code and give warnings.
73
74 =head2 Basic syntax overview
75
76 A Perl script or program consists of one or more statements.  These
77 statements are simply written in the script in a straightforward
78 fashion.  There is no need to have a C<main()> function or anything of
79 that kind.
80
81 Perl statements end in a semi-colon:
82
83     print "Hello, world";
84
85 Comments start with a hash symbol and run to the end of the line
86
87     # This is a comment
88
89 Whitespace is irrelevant:
90
91     print
92         "Hello, world"
93         ;
94
95 ... except inside quoted strings:
96
97     # this would print with a linebreak in the middle
98     print "Hello
99     world";
100
101 Double quotes or single quotes may be used around literal strings:
102
103     print "Hello, world";
104     print 'Hello, world';
105
106 However, only double quotes "interpolate" variables and special
107 characters such as newlines (C<\n>):
108
109     print "Hello, $name\n";     # works fine
110     print 'Hello, $name\n';     # prints $name\n literally
111
112 Numbers don't need quotes around them:
113
114     print 42;
115
116 You can use parentheses for functions' arguments or omit them
117 according to your personal taste.  They are only required
118 occasionally to clarify issues of precedence.
119
120     print("Hello, world\n");
121     print "Hello, world\n";
122
123 More detailed information about Perl syntax can be found in L<perlsyn>.
124
125 =head2 Perl variable types
126
127 Perl has three main variable types: scalars, arrays, and hashes.
128
129 =over 4
130
131 =item Scalars
132
133 A scalar represents a single value:
134
135     my $animal = "camel";
136     my $answer = 42;
137
138 Scalar values can be strings, integers or floating point numbers, and Perl
139 will automatically convert between them as required.  There is no need
140 to pre-declare your variable types, but you have to declare them using
141 the C<my> keyword the first time you use them. (This is one of the
142 requirements of C<use strict;>.)
143
144 Scalar values can be used in various ways:
145
146     print $animal;
147     print "The animal is $animal\n";
148     print "The square of $answer is ", $answer * $answer, "\n";
149
150 There are a number of "magic" scalars with names that look like
151 punctuation or line noise.  These special variables are used for all
152 kinds of purposes, and are documented in L<perlvar>.  The only one you
153 need to know about for now is C<$_> which is the "default variable".
154 It's used as the default argument to a number of functions in Perl, and
155 it's set implicitly by certain looping constructs.
156
157     print;          # prints contents of $_ by default
158
159 =item Arrays
160
161 An array represents a list of values:
162
163     my @animals = ("camel", "llama", "owl");
164     my @numbers = (23, 42, 69);
165     my @mixed   = ("camel", 42, 1.23);
166
167 Arrays are zero-indexed.  Here's how you get at elements in an array:
168
169     print $animals[0];              # prints "camel"
170     print $animals[1];              # prints "llama"
171
172 The special variable C<$#array> tells you the index of the last element
173 of an array:
174
175     print $mixed[$#mixed];       # last element, prints 1.23
176
177 You might be tempted to use C<$#array + 1> to tell you how many items there
178 are in an array.  Don't bother.  As it happens, using C<@array> where Perl
179 expects to find a scalar value ("in scalar context") will give you the number
180 of elements in the array:
181
182     if (@animals < 5) { ... }
183
184 The elements we're getting from the array start with a C<$> because
185 we're getting just a single value out of the array -- you ask for a scalar,
186 you get a scalar.
187
188 To get multiple values from an array:
189
190     @animals[0,1];                  # gives ("camel", "llama");
191     @animals[0..2];                 # gives ("camel", "llama", "owl");
192     @animals[1..$#animals];         # gives all except the first element
193
194 This is called an "array slice".
195
196 You can do various useful things to lists:
197
198     my @sorted    = sort @animals;
199     my @backwards = reverse @numbers;
200
201 There are a couple of special arrays too, such as C<@ARGV> (the command
202 line arguments to your script) and C<@_> (the arguments passed to a
203 subroutine).  These are documented in L<perlvar>.
204
205 =item Hashes
206
207 A hash represents a set of key/value pairs:
208
209     my %fruit_color = ("apple", "red", "banana", "yellow");
210
211 You can use whitespace and the C<< => >> operator to lay them out more
212 nicely:
213
214     my %fruit_color = (
215         apple  => "red",
216         banana => "yellow",
217     );
218
219 To get at hash elements:
220
221     $fruit_color{"apple"};           # gives "red"
222
223 You can get at lists of keys and values with C<keys()> and
224 C<values()>.
225
226     my @fruits = keys %fruit_colors;
227     my @colors = values %fruit_colors;
228
229 Hashes have no particular internal order, though you can sort the keys
230 and loop through them.
231
232 Just like special scalars and arrays, there are also special hashes.
233 The most well known of these is C<%ENV> which contains environment
234 variables.  Read all about it (and other special variables) in
235 L<perlvar>.
236
237 =back
238
239 Scalars, arrays and hashes are documented more fully in L<perldata>.
240
241 More complex data types can be constructed using references, which allow
242 you to build lists and hashes within lists and hashes.
243
244 A reference is a scalar value and can refer to any other Perl data
245 type. So by storing a reference as the value of an array or hash
246 element, you can easily create lists and hashes within lists and
247 hashes. The following example shows a 2 level hash of hash
248 structure using anonymous hash references.
249
250     my $variables = {
251         scalar  =>  {
252                      description => "single item",
253                      sigil => '$',
254                     },
255         array   =>  {
256                      description => "ordered list of items",
257                      sigil => '@',
258                     },
259         hash    =>  {
260                      description => "key/value pairs",
261                      sigil => '%',
262                     },
263     };
264
265     print "Scalars begin with a $variables->{'scalar'}->{'sigil'}\n";
266
267 Exhaustive information on the topic of references can be found in
268 L<perlreftut>, L<perllol>, L<perlref> and L<perldsc>.
269
270 =head2 Variable scoping
271
272 Throughout the previous section all the examples have used the syntax:
273
274     my $var = "value";
275
276 The C<my> is actually not required; you could just use:
277
278     $var = "value";
279
280 However, the above usage will create global variables throughout your
281 program, which is bad programming practice.  C<my> creates lexically
282 scoped variables instead.  The variables are scoped to the block
283 (i.e. a bunch of statements surrounded by curly-braces) in which they
284 are defined.
285
286     my $x = "foo";
287     my $some_condition = 1;
288     if ($some_condition) {
289         my $y = "bar";
290         print $x;           # prints "foo"
291         print $y;           # prints "bar"
292     }
293     print $x;               # prints "foo"
294     print $y;               # prints nothing; $y has fallen out of scope
295
296 Using C<my> in combination with a C<use strict;> at the top of
297 your Perl scripts means that the interpreter will pick up certain common
298 programming errors.  For instance, in the example above, the final
299 C<print $b> would cause a compile-time error and prevent you from
300 running the program.  Using C<strict> is highly recommended.
301
302 =head2 Conditional and looping constructs
303
304 Perl has most of the usual conditional and looping constructs except for
305 case/switch (but if you really want it, there is a Switch module in Perl
306 5.8 and newer, and on CPAN. See the section on modules, below, for more
307 information about modules and CPAN).
308
309 The conditions can be any Perl expression.  See the list of operators in
310 the next section for information on comparison and boolean logic operators,
311 which are commonly used in conditional statements.
312
313 =over 4
314
315 =item if
316
317     if ( condition ) {
318         ...
319     } elsif ( other condition ) {
320         ...
321     } else {
322         ...
323     }
324
325 There's also a negated version of it:
326
327     unless ( condition ) {
328         ...
329     }
330
331 This is provided as a more readable version of C<if (!I<condition>)>.
332
333 Note that the braces are required in Perl, even if you've only got one
334 line in the block.  However, there is a clever way of making your one-line
335 conditional blocks more English like:
336
337     # the traditional way
338     if ($zippy) {
339         print "Yow!";
340     }
341
342     # the Perlish post-condition way
343     print "Yow!" if $zippy;
344     print "We have no bananas" unless $bananas;
345
346 =item while
347
348     while ( condition ) {
349         ...
350     }
351
352 There's also a negated version, for the same reason we have C<unless>:
353
354     until ( condition ) {
355         ...
356     }
357
358 You can also use C<while> in a post-condition:
359
360     print "LA LA LA\n" while 1;          # loops forever
361
362 =item for
363
364 Exactly like C:
365
366     for ($i=0; $i <= $max; $i++) {
367         ...
368     }
369
370 The C style for loop is rarely needed in Perl since Perl provides
371 the more friendly list scanning C<foreach> loop.
372
373 =item foreach
374
375     foreach (@array) {
376         print "This element is $_\n";
377     }
378
379     print $list[$_] foreach 0 .. $max;
380
381     # you don't have to use the default $_ either...
382     foreach my $key (keys %hash) {
383         print "The value of $key is $hash{$key}\n";
384     }
385
386 =back
387
388 For more detail on looping constructs (and some that weren't mentioned in
389 this overview) see L<perlsyn>.
390
391 =head2 Builtin operators and functions
392
393 Perl comes with a wide selection of builtin functions.  Some of the ones
394 we've already seen include C<print>, C<sort> and C<reverse>.  A list of
395 them is given at the start of L<perlfunc> and you can easily read
396 about any given function by using C<perldoc -f I<functionname>>.
397
398 Perl operators are documented in full in L<perlop>, but here are a few
399 of the most common ones:
400
401 =over 4
402
403 =item Arithmetic
404
405     +   addition
406     -   subtraction
407     *   multiplication
408     /   division
409
410 =item Numeric comparison
411
412     ==  equality
413     !=  inequality
414     <   less than
415     >   greater than
416     <=  less than or equal
417     >=  greater than or equal
418
419 =item String comparison
420
421     eq  equality
422     ne  inequality
423     lt  less than
424     gt  greater than
425     le  less than or equal
426     ge  greater than or equal
427
428 (Why do we have separate numeric and string comparisons?  Because we don't
429 have special variable types, and Perl needs to know whether to sort
430 numerically (where 99 is less than 100) or alphabetically (where 100 comes
431 before 99).
432
433 =item Boolean logic
434
435     &&  and
436     ||  or
437     !   not
438
439 (C<and>, C<or> and C<not> aren't just in the above table as descriptions
440 of the operators -- they're also supported as operators in their own
441 right.  They're more readable than the C-style operators, but have
442 different precedence to C<&&> and friends.  Check L<perlop> for more
443 detail.)
444
445 =item Miscellaneous
446
447     =   assignment
448     .   string concatenation
449     x   string multiplication
450     ..  range operator (creates a list of numbers)
451
452 =back
453
454 Many operators can be combined with a C<=> as follows:
455
456     $a += 1;        # same as $a = $a + 1
457     $a -= 1;        # same as $a = $a - 1
458     $a .= "\n";     # same as $a = $a . "\n";
459
460 =head2 Files and I/O
461
462 You can open a file for input or output using the C<open()> function.
463 It's documented in extravagant detail in L<perlfunc> and L<perlopentut>,
464 but in short:
465
466     open(my $in,  "<",  "input.txt")  or die "Can't open input.txt: $!";
467     open(my $out, ">",  "output.txt") or die "Can't open output.txt: $!";
468     open(my $log, ">>", "my.log")     or die "Can't open my.log: $!";
469
470 You can read from an open filehandle using the C<< <> >> operator.  In
471 scalar context it reads a single line from the filehandle, and in list
472 context it reads the whole file in, assigning each line to an element of
473 the list:
474
475     my $line  = <$in>;
476     my @lines = <$in>;
477
478 Reading in the whole file at one time is called slurping. It can
479 be useful but it may be a memory hog. Most text file processing
480 can be done a line at a time with Perl's looping constructs.
481
482 The C<< <> >> operator is most often seen in a C<while> loop:
483
484     while (<$in>) {     # assigns each line in turn to $_
485         print "Just read in this line: $_";
486     }
487
488 We've already seen how to print to standard output using C<print()>.
489 However, C<print()> can also take an optional first argument specifying
490 which filehandle to print to:
491
492     print STDERR "This is your final warning.\n";
493     print $out $record;
494     print $log $logmessage;
495
496 When you're done with your filehandles, you should C<close()> them
497 (though to be honest, Perl will clean up after you if you forget):
498
499     close $in or die "$in: $!";
500
501 =head2 Regular expressions
502
503 Perl's regular expression support is both broad and deep, and is the
504 subject of lengthy documentation in L<perlrequick>, L<perlretut>, and
505 elsewhere.  However, in short:
506
507 =over 4
508
509 =item Simple matching
510
511     if (/foo/)       { ... }  # true if $_ contains "foo"
512     if ($a =~ /foo/) { ... }  # true if $a contains "foo"
513
514 The C<//> matching operator is documented in L<perlop>.  It operates on
515 C<$_> by default, or can be bound to another variable using the C<=~>
516 binding operator (also documented in L<perlop>).
517
518 =item Simple substitution
519
520     s/foo/bar/;               # replaces foo with bar in $_
521     $a =~ s/foo/bar/;         # replaces foo with bar in $a
522     $a =~ s/foo/bar/g;        # replaces ALL INSTANCES of foo with bar in $a
523
524 The C<s///> substitution operator is documented in L<perlop>.
525
526 =item More complex regular expressions
527
528 You don't just have to match on fixed strings.  In fact, you can match
529 on just about anything you could dream of by using more complex regular
530 expressions.  These are documented at great length in L<perlre>, but for
531 the meantime, here's a quick cheat sheet:
532
533     .                   a single character
534     \s                  a whitespace character (space, tab, newline)
535     \S                  non-whitespace character
536     \d                  a digit (0-9)
537     \D                  a non-digit
538     \w                  a word character (a-z, A-Z, 0-9, _)
539     \W                  a non-word character
540     [aeiou]             matches a single character in the given set
541     [^aeiou]            matches a single character outside the given set
542     (foo|bar|baz)       matches any of the alternatives specified
543
544     ^                   start of string
545     $                   end of string
546
547 Quantifiers can be used to specify how many of the previous thing you
548 want to match on, where "thing" means either a literal character, one
549 of the metacharacters listed above, or a group of characters or
550 metacharacters in parentheses.
551
552     *                   zero or more of the previous thing
553     +                   one or more of the previous thing
554     ?                   zero or one of the previous thing
555     {3}                 matches exactly 3 of the previous thing
556     {3,6}               matches between 3 and 6 of the previous thing
557     {3,}                matches 3 or more of the previous thing
558
559 Some brief examples:
560
561     /^\d+/              string starts with one or more digits
562     /^$/                nothing in the string (start and end are adjacent)
563     /(\d\s){3}/         a three digits, each followed by a whitespace
564                         character (eg "3 4 5 ")
565     /(a.)+/             matches a string in which every odd-numbered letter
566                         is a (eg "abacadaf")
567
568     # This loop reads from STDIN, and prints non-blank lines:
569     while (<>) {
570         next if /^$/;
571         print;
572     }
573
574 =item Parentheses for capturing
575
576 As well as grouping, parentheses serve a second purpose.  They can be
577 used to capture the results of parts of the regexp match for later use.
578 The results end up in C<$1>, C<$2> and so on.
579
580     # a cheap and nasty way to break an email address up into parts
581
582     if ($email =~ /([^@]+)@(.+)/) {
583         print "Username is $1\n";
584         print "Hostname is $2\n";
585     }
586
587 =item Other regexp features
588
589 Perl regexps also support backreferences, lookaheads, and all kinds of
590 other complex details.  Read all about them in L<perlrequick>,
591 L<perlretut>, and L<perlre>.
592
593 =back
594
595 =head2 Writing subroutines
596
597 Writing subroutines is easy:
598
599     sub logger {
600         my $logmessage = shift;
601         open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
602         print $logfile $logmessage;
603     }
604
605 Now we can use the subroutine just as any other built-in function:
606
607     logger("We have a logger subroutine!");
608
609 What's that C<shift>?  Well, the arguments to a subroutine are available
610 to us as a special array called C<@_> (see L<perlvar> for more on that).
611 The default argument to the C<shift> function just happens to be C<@_>.
612 So C<my $logmessage = shift;> shifts the first item off the list of
613 arguments and assigns it to C<$logmessage>.
614
615 We can manipulate C<@_> in other ways too:
616
617     my ($logmessage, $priority) = @_;       # common
618     my $logmessage = $_[0];                 # uncommon, and ugly
619
620 Subroutines can also return values:
621
622     sub square {
623         my $num = shift;
624         my $result = $num * $num;
625         return $result;
626     }
627
628 Then use it like:
629
630     $sq = square(8);
631
632 For more information on writing subroutines, see L<perlsub>.
633
634 =head2 OO Perl
635
636 OO Perl is relatively simple and is implemented using references which
637 know what sort of object they are based on Perl's concept of packages.
638 However, OO Perl is largely beyond the scope of this document.
639 Read L<perlboot>, L<perltoot>, L<perltooc> and L<perlobj>.
640
641 As a beginning Perl programmer, your most common use of OO Perl will be
642 in using third-party modules, which are documented below.
643
644 =head2 Using Perl modules
645
646 Perl modules provide a range of features to help you avoid reinventing
647 the wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ).  A
648 number of popular modules are included with the Perl distribution
649 itself.
650
651 Categories of modules range from text manipulation to network protocols
652 to database integration to graphics.  A categorized list of modules is
653 also available from CPAN.
654
655 To learn how to install modules you download from CPAN, read
656 L<perlmodinstall>
657
658 To learn how to use a particular module, use C<perldoc I<Module::Name>>.
659 Typically you will want to C<use I<Module::Name>>, which will then give
660 you access to exported functions or an OO interface to the module.
661
662 L<perlfaq> contains questions and answers related to many common
663 tasks, and often provides suggestions for good CPAN modules to use.
664
665 L<perlmod> describes Perl modules in general.  L<perlmodlib> lists the
666 modules which came with your Perl installation.
667
668 If you feel the urge to write Perl modules, L<perlnewmod> will give you
669 good advice.
670
671 =head1 AUTHOR
672
673 Kirrily "Skud" Robert <skud@cpan.org>