Perl Notes for Professionals

GoalKicker.com (CC BY-SA)
Page 1 sur 109Lecteur de document UniversityLib

Perl Notes for Professionals

Programming, Perl · notes

Voir tous les documents en programmation

Perl

Notes for ProfessionalsPerl®

Notes for Professionals

90+ pages

of professional hints and tricks

GoalKicker.com

Free Programming Books

Disclaimer

This is an unocial free book created for educational purposes and is

not aliated with ocial Perl® group(s) or company(s).

All trademarks and registered trademarks are

the property of their respective owners

Contents

About

...................................................................................................................................................................................

1

Chapter 1: Getting started with Perl Language

............................................................................................

2

Section 1.1: Getting started with Perl

............................................................................................................................

2

Chapter 2: Comments

.................................................................................................................................................

4

Section 2.1: Single-line comments

Section 2.2: Multi-line comments

................................................................................................................................

4

.................................................................................................................................

....................................................................................................................................................

........................................................................................................................................................

......................................................................................................................................

.....................................................................................................................................

.........................................................................................................................................................

Chapter 3: Variables

Section 3.1: Scalars

Section 3.2: Array References

Section 3.3: Scalar References

Section 3.4: Arrays

Section 3.5: Typeglobs, typeglob refs, filehandles and constants

Section 3.6: Sigils

Section 3.7: Hash References

Section 3.8: Hashes

............................................................................................................................................................

9

.....................................................................................................................................

.....................................................................................................................................................

...........................................................................

8

Chapter 4: Interpolation in Perl

Section 4.1: What is interpolated

Section 4.2: Basic interpolation

..........................................................................................................................

15

................................................................................................................................

..................................................................................................................................

Chapter 5: True and false

......................................................................................................................................

18

Section 5.1: List of true and false values

...................................................................................................................

18

Chapter 6: Dates and Time

Section 6.1: Date formatting

Section 6.2: Create new DateTime

Section 6.3: Working with elements of datetime

Section 6.4: Calculate code execution time

....................................................................................................................................

.......................................................................................................................................

............................................................................................................................

.....................................................................................................

19

..............................................................................................................

20

Chapter 7: Control Statements

...........................................................................................................................

21

Section 7.1: Conditionals

Section 7.2: Loops

Chapter 8: Subroutines

..............................................................................................................................................

.......................................................................................................................................................

............................................................................................................................................

23

Section 8.1: Creating subroutines

Section 8.2: Subroutines

Section 8.3: Subroutine arguments are passed by reference (except those in signatures)

.............................................................................................................................................

...............................................................................................................................

...............................

25

23

24

Chapter 9: Debug Output

.......................................................................................................................................

27

Section 9.1: Dumping with Style

Section 9.2: Dumping data-structures

Section 9.3: Data::Show

Section 9.4: Dumping array list

.................................................................................................................................

27

......................................................................................................................

28

...............................................................................................................................................

..................................................................................................................................

Chapter 10: Lists

..........................................................................................................................................................

31

.............................................................................................................................................

Section 10.1: Array as list

Section 10.2: Assigning a list to a hash

Section 10.3: Lists can be passed into subroutines

Section 10.4: Return list from subroutine

Section 10.5: Hash as list

Section 10.6: Using arrayref to pass array to sub

......................................................................................................................

..................................................................................................

31

..................................................................................................................

.............................................................................................................................................

...................................................................................................

4

5

5

5

6

7

11

12

15

16

19

19

19

21

21

28

29

Publicité

31

31

32

33

33

Chapter 11: Sorting

.....................................................................................................................................................

34

Section 11.1: Basic Lexical Sort

....................................................................................................................................

34

Section 11.2: The Schwartzian Transform

Section 11.3: Case Insensitive Sort

Section 11.4: Numeric Sort

Section 11.5: Reverse Sort

.................................................................................................................

34

..............................................................................................................................

...........................................................................................................................................

...........................................................................................................................................

...........................................................................................

......................................................................................................

Chapter 12: File I/O (reading and writing files)

Section 12.1: Opening A FileHandle for Reading

Section 12.2: Reading from a file

Section 12.3: Write to a file

Section 12.4: "use autodie" and you won't need to check file open/close failures

Section 12.5: Rewind a filehandle

Section 12.6: Reading and Writing gzip compressed files

Section 12.7: Setting the default Encoding for IO

...............................................................................................................................

.......................................................................................

.....................................................................................................

...............................................................................................................................

..........................................................................................................................................

..............................................

37

Chapter 13: Reading a file's content into a variable

................................................................................

40

Section 13.1: Path::Tiny

Section 13.2: The manual way

Section 13.3: File::Slurp

Section 13.4: File::Slurper

Section 13.5: Slurping a file into an array variable

Section 13.6: Slurp file in one-liner

.................................................................................................................................................

....................................................................................................................................

.................................................................................................................................................

.............................................................................................................................................

..............................................................................................................................

41

...................................................................................................

41

Chapter 14: Strings and quoting methods

....................................................................................................

42

Section 14.1: String Literal Quoting

Section 14.2: Double-quoting

Section 14.3: Heredocs

Section 14.4: Removing trailing newlines

.............................................................................................................................

......................................................................................................................................

................................................................................................................................................

..................................................................................................................

44

Chapter 15: Split a string on unquoted separators

...................................................................................

46

Section 15.1: parse_line()

Section 15.2: Text::CSV or Text::CSV_XS

............................................................................................................................................

46

....................................................................................................................

46

Chapter 16: Object-oriented Perl

........................................................................................................................

47

Section 16.1: Defining classes in modern Perl

Section 16.2: Creating Objects

Section 16.3: Defining Classes

Section 16.4: Inheritance and methods resolution

Section 16.5: Class and Object Methods

Section 16.6: Roles

...........................................................................................................

....................................................................................................................................

....................................................................................................................................

...................................................................................................

49

....................................................................................................................

.......................................................................................................................................................

Chapter 17: Exception handling

...........................................................................................................................

54

Section 17.1: eval and die

............................................................................................................................................

54

Chapter 18: Regular Expressions

........................................................................................................................

55

Section 18.1: Replace a string using regular expressions

Section 18.2: Matching strings

Section 18.3: Parsing a string with a regex

Section 18.4: Usage of \Q and \E in pattern matching

....................................................................................................................................

........................................................................................

55

...............................................................................................................

...........................................................................................

Chapter 19: XML Parsing

..........................................................................................................................................

57

Section 19.1: Parsing with XML::Twig

Section 19.2: Consuming XML with XML::Rabbit

Section 19.3: Parsing with XML::LibXML

..........................................................................................................................

57

.......................................................................................................

58

.....................................................................................................................

60

Chapter 20: Unicode

..................................................................................................................................................

62

Section 20.1: The utf8 pragma: using Unicode in your sources

Section 20.2: Handling invalid UTF-8

Section 20.3: Command line switches for one-liners

........................................................................................................................

...............................................................................................

.............................................................................

62

35

35

35

36

36

36

37

38

38

Publicité

39

40

40

40

41

42

42

43

47

47

48

51

52

55

55

56

62

63

Section 20.4: Standard I/O

Section 20.5: File handles

Section 20.6: Create filenames

Section 20.7: Read filenames

Chapter 21: Perl one-liners

.........................................................................................................................................

...........................................................................................................................................

..................................................................................................................................

65

.....................................................................................................................................

.....................................................................................................................................

...................................................................................................................

Section 21.1: Upload file into mojolicious

Section 21.2: Execute some Perl code from command line

Section 21.3: Using double-quoted strings in Windows one-liners

Section 21.4: Print lines matching a pattern (PCRE grep)

Section 21.5: Replace a substring with another (PCRE sed)

Section 21.6: Print only certain fields

Section 21.7: Print lines 5 to 10

Section 21.8: Edit file in-place

Section 21.9: Reading the whole file as a string

.........................................................................................................................

....................................................................................................................................

.....................................................................................................................................

.......................................................................................................

....................................................................................

.........................................................................

68

.......................................................................................

...................................................................................

Chapter 22: Randomness

........................................................................................................................................

70

Section 22.1: Accessing an array element at random

Section 22.2: Generate a random integer between 0 and 9

.............................................................................................

70

..................................................................................

70

Chapter 23: Special variables

...............................................................................................................................

71

Section 23.1: Special variables in perl:

Chapter 24: Packages and modules

.......................................................................................................................

71

.................................................................................................................

72

Section 24.1: Using a module

Section 24.2: Using a module inside a directory

Section 24.3: Loading a module at runtime

Section 24.4: CPAN.pm

Section 24.5: List all installed modules

Section 24.6: Executing the contents of another file

.....................................................................................................................................

......................................................................................................

..............................................................................................................

................................................................................................................................................

......................................................................................................................

...............................................................................................

74

Chapter 25: Install Perl modules via CPAN

....................................................................................................

75

Section 25.1: cpanminus, the lightweight configuration-free replacement for cpan

Section 25.2: Installing modules manually

Section 25.3: Run Perl CPAN in your terminal (Mac and Linux) or command prompt (Windows)

...............................................................................................................

...........................................

....................

76

75

75

Chapter 26: Easy way to check installed modules on Mac and Ubuntu

.........................................

78

Section 26.1: Use perldoc to check the Perl package install path

Section 26.2: Check installed perl modules via terminal

Section 26.3: How to check Perl corelist modules

.........................................................................................

....................................................................................................

..........................................................................

78

Chapter 27: Pack and unpack

..............................................................................................................................

79

Section 27.1: Manually Converting C Structs to Pack Syntax

Section 27.2: Constructing an IPv4 header

..................................................................................

79

...............................................................................................................

80

Chapter 28: Perl commands for Windows Excel with Win32::OLE module

....................................

82

Section 28.1: Opening and Saving Excel/Workbooks

Section 28.2: Manipulation of Worksheets

Section 28.3: Manipulation of cells

Section 28.4: Manipulation of Rows / Columns

...............................................................................................................

............................................................................................................................

.......................................................................................................

..............................................................................................

82

Chapter 29: Simple interaction with database via DBI module

..........................................................

85

Section 29.1: DBI module

Chapter 30: Perl Testing

............................................................................................................................................

85

.........................................................................................................................................

87

Section 30.1: Perl Unit Testing Example

....................................................................................................................

87

Chapter 31: Dancer

.....................................................................................................................................................

89

Section 31.1: Easiest example

......................................................................................................................................

89

Publicité

64

64

66

68

68

68

68

69

69

69

69

69

72

72

73

73

74

78

78

82

83

84

Chapter 32: Attributed Text

...................................................................................................................................

90

Section 32.1: Printing colored Text

Chapter 33: GUI Applications in Perl

.............................................................................................................................

90

..................................................................................................................

91

Section 33.1: GTK Application

.....................................................................................................................................

91

Chapter 34: Memory usage optimization

Section 34.1: Reading files: foreach vs. while

Section 34.2: Processing long lists

Chapter 35: Perl script debugging

Section 35.1: Run script in debug mode

Section 35.2: Use a nonstandard debugger

......................................................................................................

92

............................................................................................................

.............................................................................................................................

.....................................................................................................................

....................................................................................................................

.............................................................................................................

Chapter 36: Perlbrew

................................................................................................................................................

94

Section 36.1: Setup perlbrew for the first time

..........................................................................................................

94

Chapter 37: Installation of Perl

...........................................................................................................................

95

Section 37.1: Linux

Section 37.2: OS X

Section 37.3: Windows

........................................................................................................................................................

........................................................................................................................................................

.................................................................................................................................................

96

Chapter 38: Compile Perl cpan module sapnwrfc from source code

..............................................

97

Section 38.1: Simple example to test the RFC connection

.......................................................................................

97

Chapter 39: Best Practices

Section 39.1: Using Perl::Critic

.....................................................................................................................................

98

.....................................................................................................................................

98

Credits

............................................................................................................................................................................

102

You may also like

......................................................................................................................................................

104

92

92

93

93

93

95

95

About

Please feel free to share this PDF with anyone for free,

latest version of this book can be downloaded from:

https://goalkicker.com/PerlBook

This Perl® Notes for Professionals book is compiled from Stack Overflow

Documentation, the content is written by the beautiful people at Stack Overflow.

Text content is released under Creative Commons BY-SA, see credits at the end

of this book whom contributed to the various chapters. Images may be copyright

of their respective owners unless otherwise specified

This is an unofficial free book created for educational purposes and is not

affiliated with official Perl® group(s) or company(s) nor Stack Overflow. All

trademarks and registered trademarks are the property of their respective

company owners

The information presented in this book is not guaranteed to be correct nor

accurate, use at your own risk

Please send feedback and corrections to [email protected]

GoalKicker.com – Perl® Notes for Professionals

1

Chapter 1: Getting started with Perl

Language

Version Release Notes Release Date

1.000

1987-12-18

2.000

3.000

4.000

5.000

5.001

5.002

5.003

1988-06-05

1989-10-18

1991-03-21

1994-10-17

1995-05-13

1996-02-29

1996-06-25

5.004

perl5004delta 1997-05-15

5.005

perl5005delta 1998-07-22

5.6.0

5.8.0

perl56delta

2000-03-22

perl58delta

2002-07-18

5.8.8

perl581delta,

perl582delta,

perl583delta,

perl584delta,

Publicité

perl585delta,

perl586delta,

perl587delta,

perl588delta

2006-02-01

5.10.0 perl5100delta 2007-12-18

5.12.0 perl5120delta 2010-04-12

5.14.0 perl5140delta 2011-05-14

5.16.0 perl5160delta 2012-05-20

5.18.0 perl5180delta 2013-05-18

5.20.0 perl5200delta 2014-05-27

5.22.0 perl5220delta 2015-06-01

5.24.0 perl5240delta 2016-05-09

5.26.0 perl5260delta 2017-05-30

Section 1.1: Getting started with Perl

Perl tries to do what you mean:

print "Hello World\n";

The two tricky bits are the semicolon at the end of the line and the \n, which adds a newline (line feed). If you have

a relatively new version of perl, you can use say instead of print to have the carriage return added automatically:

Version ≥ 5.10.0

use feature 'say';

say "Hello World";

The say feature is also enabled automatically with a use v5.10 (or higher) declaration:

use v5.10;

GoalKicker.com – Perl® Notes for Professionals

2

say "Hello World";

It's pretty common to just use perl on the command line using the -e option:

$ perl -e 'print "Hello World\n"'

Hello World

Adding the -l option is one way to print newlines automatically:

$ perl -le 'print "Hello World"'

Hello World

Version ≥ 5.10.0

If you want to enable new features, use the -E option instead:

$ perl -E 'say "Hello World"'

Hello World

You can also, of course, save the script in a file. Just remove the -e command line option and use the filename of

the script: perl script.pl. For programs longer than a line, it's wise to turn on a couple of options:

use strict;

use warnings;

print "Hello World\n";

There's no real disadvantage other than making the code slightly longer. In exchange, the strict pragma prevents

you from using code that is potentially unsafe and warnings notifies you of many common errors.

Notice the line-ending semicolon is optional for the last line, but is a good idea in case you later add to the end of

your code.

For more options how to run Perl, see perlrun or type perldoc perlrun at a command prompt. For a more detailed

introduction to Perl, see perlintro or type perldoc perlintro at a command prompt. For a quirky interactive

tutorial, Try Perl.

GoalKicker.com – Perl® Notes for Professionals

3

Chapter 2: Comments

Section 2.1: Single-line comments

Single-line comments begin with a pound sign # and go to the end of the line:

This is a comment

my $foo = "bar"; # This is also a comment

Section 2.2: Multi-line comments

Multi-line comments start with = and with the =cut statement. These are special comments called POD (Plain Old

Documentation).

Any text between the markers will be commented out:

=begin comment

This is another comment.

And it spans multiple lines!

=end comment

=cut

GoalKicker.com – Perl® Notes for Professionals

4

Chapter 3: Variables

Section 3.1: Scalars

Scalars are Perl's most basic data type. They're marked with the sigil $ and hold a single value of one of three types:

a number (3, 42, 3.141, etc.)

a string ('hi', "abc", etc.)

a reference to a variable (see other examples).

my $integer = 3; # number

my $string = "Hello World"; # string

my $reference = \$string; # reference to $string

Perl converts between numbers and strings on the fly, based on what a particular operator expects.

my $number = '41'; # string '41'

my $meaning = $number + 1; # number 42

my $sadness = '20 apples'; # string '20 apples'

my $danger = $sadness * 2; # number '40', raises warning

When converting a string into a number, Perl takes as many digits from the front of a string as it can – hence why 20

apples is converted into 20 in the last line.

Based on whether you want to treat the contents of a scalar as a string or a number, you need to use different

operators. Do not mix them.

String comparison # Number comparison

'Potato' eq 'Potato'; 42 == 42;

'Potato' ne 'Pomato'; 42 != 24;

'Camel' lt 'Potato'; 41 < 42;

'Zombie' gt 'Potato'; 43 > 42;

String concatenation # Number summation

'Banana' . 'phone'; 23 + 19;

String repetition # Number multiplication

'nan' x 3; 6 * 7;

Attempting to use string operations on numbers will not raise warnings; attempting to use number operations on

non-numeric strings will. Do be aware that some non-digit strings such as 'inf', 'nan', '0 but true' count as

numbers.

Section 3.2: Array References

Array References are scalars ($) which refer to Arrays.

my @array = ("Hello"); # Creating array, assigning value from a list

my $array_reference = \@array;

These can be created more short-hand as follows:

my $other_array_reference = ["Hello"];

Modifying / Using array references require dereferencing them first.

GoalKicker.com – Perl® Notes for Professionals

5

my @contents = @{ $array_reference }; # Prefix notation

my @contents = @$array_reference; # Braces can be left out

Version ≥ 5.24.0

New postfix dereference syntax, available by default from v5.24

use v5.24;

my @contents = $array_reference->@*; # New postfix notation

When accessing an arrayref's contents by index you can use the -> syntactical sugar.

my @array = qw(one two three); my $arrayref = [ qw(one two three) ]

my $one = $array[0]; my $one = $arrayref->[0];

Unlike arrays, arrayrefs can be nested:

my @array = ( (1, 0), (0, 1) ) # ONE array of FOUR elements: (1, 0, 0, 1)

my @matrix = ( [1, 0], [0, 1] ) # an array of two arrayrefs

my $matrix = [ [0, 1], [1, 0] ] # an arrayref of arrayrefs

There is no namespace conflict between scalars, arrays and hashes

so @matrix and $matrix _both_ exist at this point and hold different values.

my @diagonal_1 = ($matrix[0]->[1], $matrix[1]->[0]) # uses @matrix

my @diagonal_2 = ($matrix->[0]->[1], $matrix->[1]->[0]) # uses $matrix

Since chained []- and {}-access can only happen on references, you can

omit some of those arrows.

my $corner_1 = $matrix[0][1]; # uses @matrix;

my $corner_2 = $matrix->[0][1]; # uses $matrix;

When used as Boolean, references are always true.

Section 3.3: Scalar References

A reference is a scalar variable (one prefixed by $ ) which “refers to” some other data.

my $value = "Hello";

my $reference = \$value;

print $value; # => Hello

print $reference; # => SCALAR(0x2683310)

To get the referred-to data, you de-reference it.

say ${$reference}; # Explicit prefix syntax

say $$reference; # The braces can be left out (confusing)

Version ≥ 5.24.0

New postfix dereference syntax, available by default from v5.24

use v5.24;

Publicité

say $reference->$*; # New post...