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