Debian Codegraph @

upstream/debian-unstable/man1/perlintro.1

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