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