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