Debian Codegraph @

upstream/fedora-44/man1/perlintro.1

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