Statistics
28
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-01-05

AuthorGoalKicker.com

No description

Tags
No tags
Publisher: GoalKicker.com
Publish Year: 2018
Language: 英文
Pages: 109
File Format: PDF
File Size: 1.2 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Perl Notes for ProfessionalsPerl® Notes for Professionals 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 90+ pages of professional hints and tricks
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 4 ................................................................................................................................ Section 2.2: Multi-line comments 4 ................................................................................................................................. Chapter 3: Variables 5 .................................................................................................................................................... Section 3.1: Scalars 5 ........................................................................................................................................................ Section 3.2: Array References 5 ...................................................................................................................................... Section 3.3: Scalar References 6 ..................................................................................................................................... Section 3.4: Arrays 7 ......................................................................................................................................................... Section 3.5: Typeglobs, typeglob refs, filehandles and constants 8 ........................................................................... Section 3.6: Sigils 9 ............................................................................................................................................................ Section 3.7: Hash References 11 ..................................................................................................................................... Section 3.8: Hashes 12 ..................................................................................................................................................... Chapter 4: Interpolation in Perl 15 .......................................................................................................................... Section 4.1: What is interpolated 15 ................................................................................................................................ Section 4.2: Basic interpolation 16 .................................................................................................................................. Chapter 5: True and false 18 ...................................................................................................................................... Section 5.1: List of true and false values 18 ................................................................................................................... Chapter 6: Dates and Time 19 .................................................................................................................................... Section 6.1: Date formatting 19 ....................................................................................................................................... Section 6.2: Create new DateTime 19 ............................................................................................................................ Section 6.3: Working with elements of datetime 19 ..................................................................................................... Section 6.4: Calculate code execution time 20 .............................................................................................................. Chapter 7: Control Statements 21 ........................................................................................................................... Section 7.1: Conditionals 21 .............................................................................................................................................. Section 7.2: Loops 21 ....................................................................................................................................................... Chapter 8: Subroutines 23 ............................................................................................................................................ Section 8.1: Creating subroutines 23 ............................................................................................................................... Section 8.2: Subroutines 24 ............................................................................................................................................. Section 8.3: Subroutine arguments are passed by reference (except those in signatures) 25 ............................... Chapter 9: Debug Output 27 ....................................................................................................................................... Section 9.1: Dumping with Style 27 ................................................................................................................................. Section 9.2: Dumping data-structures 28 ...................................................................................................................... Section 9.3: Data::Show 28 ............................................................................................................................................... Section 9.4: Dumping array list 29 .................................................................................................................................. Chapter 10: Lists 31 .......................................................................................................................................................... Section 10.1: Array as list 31 ............................................................................................................................................. Section 10.2: Assigning a list to a hash 31 ...................................................................................................................... Section 10.3: Lists can be passed into subroutines 31 .................................................................................................. Section 10.4: Return list from subroutine 32 .................................................................................................................. Section 10.5: Hash as list 33 ............................................................................................................................................. Section 10.6: Using arrayref to pass array to sub 33 ................................................................................................... Chapter 11: Sorting 34 ..................................................................................................................................................... Section 11.1: Basic Lexical Sort 34 ....................................................................................................................................
Section 11.2: The Schwartzian Transform 34 ................................................................................................................. Section 11.3: Case Insensitive Sort 35 .............................................................................................................................. Section 11.4: Numeric Sort 35 ........................................................................................................................................... Section 11.5: Reverse Sort 35 ........................................................................................................................................... Chapter 12: File I/O (reading and writing files) 36 ........................................................................................... Section 12.1: Opening A FileHandle for Reading 36 ...................................................................................................... Section 12.2: Reading from a file 36 ............................................................................................................................... Section 12.3: Write to a file 37 .......................................................................................................................................... Section 12.4: "use autodie" and you won't need to check file open/close failures 37 .............................................. Section 12.5: Rewind a filehandle 38 ............................................................................................................................... Section 12.6: Reading and Writing gzip compressed files 38 ....................................................................................... Section 12.7: Setting the default Encoding for IO 39 ..................................................................................................... Chapter 13: Reading a file's content into a variable 40 ................................................................................ Section 13.1: Path::Tiny 40 ................................................................................................................................................. Section 13.2: The manual way 40 .................................................................................................................................... Section 13.3: File::Slurp 40 ................................................................................................................................................. Section 13.4: File::Slurper 41 ............................................................................................................................................. Section 13.5: Slurping a file into an array variable 41 ................................................................................................... Section 13.6: Slurp file in one-liner 41 .............................................................................................................................. Chapter 14: Strings and quoting methods 42 .................................................................................................... Section 14.1: String Literal Quoting 42 ............................................................................................................................. Section 14.2: Double-quoting 42 ...................................................................................................................................... Section 14.3: Heredocs 43 ................................................................................................................................................ Section 14.4: Removing trailing newlines 44 .................................................................................................................. Chapter 15: Split a string on unquoted separators 46 ................................................................................... Section 15.1: parse_line() 46 ............................................................................................................................................ Section 15.2: Text::CSV or Text::CSV_XS 46 .................................................................................................................... Chapter 16: Object-oriented Perl 47 ........................................................................................................................ Section 16.1: Defining classes in modern Perl 47 ........................................................................................................... Section 16.2: Creating Objects 47 .................................................................................................................................... Section 16.3: Defining Classes 48 .................................................................................................................................... Section 16.4: Inheritance and methods resolution 49 ................................................................................................... Section 16.5: Class and Object Methods 51 .................................................................................................................... Section 16.6: Roles 52 ....................................................................................................................................................... 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 55 ........................................................................................ Section 18.2: Matching strings 55 .................................................................................................................................... Section 18.3: Parsing a string with a regex 55 ............................................................................................................... Section 18.4: Usage of \Q and \E in pattern matching 56 ........................................................................................... Chapter 19: XML Parsing 57 .......................................................................................................................................... Section 19.1: Parsing with XML::Twig 57 .......................................................................................................................... Section 19.2: Consuming XML with XML::Rabbit 58 ....................................................................................................... Section 19.3: Parsing with XML::LibXML 60 ..................................................................................................................... Chapter 20: Unicode 62 .................................................................................................................................................. Section 20.1: The utf8 pragma: using Unicode in your sources 62 ............................................................................. Section 20.2: Handling invalid UTF-8 62 ........................................................................................................................ Section 20.3: Command line switches for one-liners 63 ...............................................................................................
Section 20.4: Standard I/O 64 ......................................................................................................................................... Section 20.5: File handles 64 ........................................................................................................................................... Section 20.6: Create filenames 65 .................................................................................................................................. Section 20.7: Read filenames 66 ..................................................................................................................................... Chapter 21: Perl one-liners 68 ..................................................................................................................................... Section 21.1: Upload file into mojolicious 68 ................................................................................................................... Section 21.2: Execute some Perl code from command line 68 .................................................................................... Section 21.3: Using double-quoted strings in Windows one-liners 68 ......................................................................... Section 21.4: Print lines matching a pattern (PCRE grep) 68 ....................................................................................... Section 21.5: Replace a substring with another (PCRE sed) 69 ................................................................................... Section 21.6: Print only certain fields 69 ......................................................................................................................... Section 21.7: Print lines 5 to 10 69 .................................................................................................................................... Section 21.8: Edit file in-place 69 ..................................................................................................................................... Section 21.9: Reading the whole file as a string 69 ....................................................................................................... Chapter 22: Randomness 70 ........................................................................................................................................ Section 22.1: Accessing an array element at random 70 ............................................................................................. Section 22.2: Generate a random integer between 0 and 9 70 .................................................................................. Chapter 23: Special variables 71 ............................................................................................................................... Section 23.1: Special variables in perl: 71 ....................................................................................................................... Chapter 24: Packages and modules 72 ................................................................................................................. Section 24.1: Using a module 72 ..................................................................................................................................... Section 24.2: Using a module inside a directory 72 ...................................................................................................... Section 24.3: Loading a module at runtime 73 .............................................................................................................. Section 24.4: CPAN.pm 73 ................................................................................................................................................ Section 24.5: List all installed modules 74 ...................................................................................................................... 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 75 ........................................... Section 25.2: Installing modules manually 75 ............................................................................................................... Section 25.3: Run Perl CPAN in your terminal (Mac and Linux) or command prompt (Windows) 76 .................... 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 78 .......................................................................... Section 26.2: Check installed perl modules via terminal 78 ......................................................................................... 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 79 .................................................................................. Section 27.2: Constructing an IPv4 header 80 ............................................................................................................... Chapter 28: Perl commands for Windows Excel with Win32::OLE module 82 .................................... Section 28.1: Opening and Saving Excel/Workbooks 82 .............................................................................................. Section 28.2: Manipulation of Worksheets 82 ............................................................................................................... Section 28.3: Manipulation of cells 83 ............................................................................................................................ Section 28.4: Manipulation of Rows / Columns 84 ....................................................................................................... Chapter 29: Simple interaction with database via DBI module 85 .......................................................... Section 29.1: DBI module 85 ............................................................................................................................................ Chapter 30: Perl Testing 87 ......................................................................................................................................... Section 30.1: Perl Unit Testing Example 87 .................................................................................................................... Chapter 31: Dancer 89 ..................................................................................................................................................... Section 31.1: Easiest example 89 ......................................................................................................................................
Chapter 32: Attributed Text 90 ................................................................................................................................... Section 32.1: Printing colored Text 90 ............................................................................................................................. Chapter 33: GUI Applications in Perl 91 .................................................................................................................. Section 33.1: GTK Application 91 ..................................................................................................................................... Chapter 34: Memory usage optimization 92 ...................................................................................................... Section 34.1: Reading files: foreach vs. while 92 ............................................................................................................ Section 34.2: Processing long lists 92 ............................................................................................................................. Chapter 35: Perl script debugging 93 ..................................................................................................................... Section 35.1: Run script in debug mode 93 .................................................................................................................... Section 35.2: Use a nonstandard debugger 93 ............................................................................................................. Chapter 36: Perlbrew 94 ................................................................................................................................................ Section 36.1: Setup perlbrew for the first time 94 .......................................................................................................... Chapter 37: Installation of Perl 95 ........................................................................................................................... Section 37.1: Linux 95 ........................................................................................................................................................ Section 37.2: OS X 95 ........................................................................................................................................................ 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 98 ..................................................................................................................................... Section 39.1: Using Perl::Critic 98 ..................................................................................................................................... Credits 102 ............................................................................................................................................................................ You may also like 104 ......................................................................................................................................................
GoalKicker.com – Perl® Notes for Professionals 1 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 web@petercv.com
GoalKicker.com – Perl® Notes for Professionals 2 Chapter 1: Getting started with Perl Language Version Release Notes Release Date 1.000 1987-12-18 2.000 1988-06-05 3.000 1989-10-18 4.000 1991-03-21 5.000 1994-10-17 5.001 1995-05-13 5.002 1996-02-29 5.003 1996-06-25 5.004 perl5004delta 1997-05-15 5.005 perl5005delta 1998-07-22 5.6.0 perl56delta 2000-03-22 5.8.0 perl58delta 2002-07-18 5.8.8 perl581delta, perl582delta, perl583delta, perl584delta, 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 3 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 4 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 5 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 6 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; say $reference->$*; # New postfix notation This "de-referenced value" can then be changed like it was the original variable. ${$reference} =~ s/Hello/World/; print ${$reference}; # => World print $value; # => World
GoalKicker.com – Perl® Notes for Professionals 7 A reference is always truthy – even if the value it refers to is falsy (like 0 or ""). You may want a Scalar Reference If: You want to pass a string to a function, and have it modify that string for you without it being a return value. You wish to explicitly avoid Perl implicitly copying the contents of a large string at some point in your function passing ( especially relevant on older Perls without copy-on-write strings ) You wish to disambiguate string-like values with specific meaning, from strings that convey content, for example: Disambiguate a file name from file content Disambiguate returned content from a returned error string You wish to implement a lightweight inside out object model, where objects handed to calling code don't carry user visible metadata: our %objects; my $next_id = 0; sub new { my $object_id = $next_id++; $objects{ $object_id } = { ... }; # Assign data for object my $ref = \$object_id; return bless( $ref, "MyClass" ); } Section 3.4: Arrays Arrays store an ordered sequence of values. You can access the contents by index, or iterate over them. The values will stay in the order you filled them in. my @numbers_to_ten = (1,2,3,4,5,6,7,8,9,10); # More conveniently: (1..10) my @chars_of_hello = ('h','e','l','l','o'); my @word_list = ('Hello','World'); # Note the sigil: access an @array item with $array[index] my $second_char_of_hello = $chars_of_hello[1]; # 'e' # Use negative indices to count from the end (with -1 being last) my $last_char_of_hello = $chars_of_hello[-1]; # Assign an array to a scalar to get the length of the array my $length_of_array = @chars_of_hello; # 5 # You can use $# to get the last index of an array, and confuse Stack Overflow my $last_index_of_array = $#chars_of_hello; # 4 # You can also access multiple elements of an array at the same time # This is called "array slice" # Since this returns multiple values, the sigil to use here on the RHS is @ my @some_chars_of_hello = @chars_of_hello[1..3]; # ('H', 'e', 'l') my @out_of_order_chars = @chars_of_hello[1,4,2]; # ('e', 'o', 'l') # In Python you can say array[1:-1] to get all elements but first and last # Not so in Perl: (1..-1) is an empty list. Use $# instead my @empty_list = @chars_of_hello[1..-1]; # () my @inner_chars_of_hello = @chars_of_hello[1..$#chars_of_hello-1]; # ('e','l','l')
GoalKicker.com – Perl® Notes for Professionals 8 # Access beyond the end of the array yields undef, not an error my $undef = $chars_of_hello[6]; # undef Arrays are mutable: use utf8; # necessary because this snippet is utf-8 $chars_of_hello[1] = 'u'; # ('h','u','l','l','o') push @chars_of_hello, ('!', '!'); # ('h','u','l','l','o','!','!') pop @chars_of_hello; # ('h','u','l','l','o','!') shift @chars_of_hello; # ('u','l','l','o','!') unshift @chars_of_hello, ('¡', 'H'); # ('¡','H','u','l','l','o','!') @chars_of_hello[2..5] = ('O','L','A'); # ('¡','H','O','L','A',undef,'!') whoops! delete $chars_of_hello[-2]; # ('¡','H','O','L','A', '!') # Setting elements beyond the end of an array does not result in an error # The array is extended with undef's as necessary. This is "autovivification." my @array; # () my @array[3] = 'x'; # (undef, undef, undef, 'x') Finally, you can loop over the contents of an array: use v5.10; # necessary for 'say' for my $number (@numbers_to_ten) { say $number ** 2; } When used as booleans, arrays are true if they are not empty. Section 3.5: Typeglobs, typeglob refs, filehandles and constants A typeglob *foo holds references to the contents of global variables with that name: $foo, @foo, $foo, &foo, etc. You can access it like an hash and assign to manipulate the symbol tables directly (evil!). use v5.10; # necessary for say our $foo = "foo"; our $bar; say ref *foo{SCALAR}; # SCALAR say ${ *foo{SCALAR} }; # bar *bar = *foo; say $bar; # bar $bar = 'egg'; say $foo; # egg Typeglobs are more commonly handled when dealing with files. open, for example, produces a reference to a typeglob when asked to create a non-global filehandle: use v5.10; # necessary for say open(my $log, '> utf-8', '/tmp/log') or die $!; # open for writing with encoding say $log 'Log opened'; # You can dereference this globref, but it's not very useful. say ref $log; # GLOB say (*{$log}->{IO} // 'undef'); # undef close $log or die $!;
GoalKicker.com – Perl® Notes for Professionals 9 Typeglobs can also be used to make global read-only variables, though use constant is in broader use. # Global constant creation *TRUE = \('1'); our $TRUE; say $TRUE; # 1 $TRUE = ''; # dies, "Modification of a read-only value attempted" # use constant instead defines a parameterless function, therefore it's not global, # can be used without sigils, can be imported, but does not interpolate easily. use constant (FALSE => 0); say FALSE; # 0 say &FALSE; # 0 say "${\FALSE}"; # 0 (ugh) say *FALSE{CODE}; # CODE(0xMA1DBABE) # Of course, neither is truly constant when you can manipulate the symbol table... *TRUE = \(''); use constant (EVIL => 1); *FALSE = *EVIL; Section 3.6: Sigils Perl has a number of sigils: $scalar = 1; # individual value @array = ( 1, 2, 3, 4, 5 ); # sequence of values %hash = ('it', 'ciao', 'en', 'hello', 'fr', 'salut'); # unordered key-value pairs &function('arguments'); # subroutine *typeglob; # symbol table entry These look like sigils, but aren't: \@array; # \ returns the reference of what's on the right (so, a reference to @array) $#array; # this is the index of the last element of @array You can use braces after the sigil if you should be so inclined. Occasionally, this improves readability. say ${value} = 5; While you use different sigils to define variables of different types, the same variable can be accessed in different ways based on what sigils you use. %hash; # we use % because we are looking at an entire hash $hash{it}; # we want a single value, however, that's singular, so we use $ $array[0]; # likewise for an array. notice the change in brackets. @array[0,3]; # we want multiple values of an array, so we instead use @ @hash{'it','en'}; # similarly for hashes (this gives the values: 'ciao', 'hello') %hash{'it','fr'}; # we want an hash with just some of the keys, so we use % # (this gives key-value pairs: 'it', 'ciao', 'fr', 'salut') This is especially true of references. In order to use a referenced value you can combine sigils together. my @array = 1..5; # This is an array my $reference_to_an_array = \@array; # A reference to an array is a singular value push @array, 6; # push expects an array push @$reference_to_an_array, 7; # the @ sigil means what's on the right is an array # and what's on the right is $reference_to_an_array
GoalKicker.com – Perl® Notes for Professionals 10 # hence: first a @, then a $ Here's a perhaps less confusing way to think about it. As we saw earlier, you can use braces to wrap what's on the right of a sigil. So you can think of @{} as something that takes an array reference and gives you the referenced array. # pop does not like array references pop $reference_to_an_array; # ERROR in Perl 5.20+ # but if we use @{}, then... pop @{ $reference_to_an_array }; # this works! As it turns out, @{} actually accepts an expression: my $values = undef; say pop @{ $values }; # ERROR: can't use undef as an array reference say pop @{ $values // [5] } # undef // [5] gives [5], so this prints 5 ...and the same trick works for other sigils, too. # This is not an example of good Perl. It is merely a demonstration of this language feature my $hashref = undef; for my $key ( %{ $hashref // {} } ) { "This doesn't crash"; } ...but if the "argument" to a sigil is simple, you can leave the braces away. say $$scalar_reference; say pop @$array_reference; for keys (%$hash_reference) { ... }; Things can get excessively extravagant. This works, but please Perl responsibly. my %hash = (it => 'ciao', en => 'hi', fr => 'salut'); my $reference = \%hash; my $reference_to_a_reference = \$reference; my $italian = $hash{it}; # Direct access my @greets = @$reference{'it', 'en'}; # Dereference, then access as array my %subhash = %$$reference_to_a_reference{'en', 'fr'} # Dereference ×2 then access as hash For most normal use, you can just use subroutine names without a sigil. (Variables without a sigil are typically called "barewords".) The & sigil is only useful in a limited number of cases. Making a reference to a subroutine: sub many_bars { 'bar' x $_[0] } my $reference = \&many_bars; say $reference->(3); # barbarbar Calling a function ignoring its prototype. Combined with goto, as a slightly weird function call that has the current call frame replaced with the caller. Think the linux exec() API call, but for functions.
GoalKicker.com – Perl® Notes for Professionals 11 Section 3.7: Hash References Hash references are scalars which contain a pointer to the memory location containing the data of a hash. Because the scalar points directly to the hash itself, when it is passed to a subroutine, changes made to the hash are not local to the subroutine as with a regular hash, but instead are global. First, let's examine what happens when you pass a normal hash to a subroutine and modify it within there: use strict; use warnings; use Data::Dumper; sub modify { my %hash = @_; $hash{new_value} = 2; print Dumper("Within the subroutine"); print Dumper(\%hash); return; } my %example_hash = ( old_value => 1, ); modify(%example_hash); print Dumper("After exiting the subroutine"); print Dumper(\%example_hash); Which results in: $VAR1 = 'Within the subroutine'; $VAR1 = { 'new_value' => 2, 'old_value' => 1 }; $VAR1 = 'After exiting the subroutine'; $VAR1 = { 'old_value' => 1 }; Notice that after we exit the subroutine, the hash remains unaltered; all changes to it were local to the modify subroutine, because we passed a copy of the hash, not the hash itself. In comparison, when you pass a hashref, you are passing the address to the original hash, so any changes made within the subroutine will be made to the original hash: use strict; use warnings; use Data::Dumper; sub modify { my $hashref = shift;
GoalKicker.com – Perl® Notes for Professionals 12 # De-reference the hash to add a new value $hashref->{new_value} = 2; print Dumper("Within the subroutine"); print Dumper($hashref); return; } # Create a hashref my $example_ref = { old_value => 1, }; # Pass a hashref to a subroutine modify($example_ref); print Dumper("After exiting the subroutine"); print Dumper($example_ref); This will result in: $VAR1 = 'Within the subroutine'; $VAR1 = { 'new_value' => 2, 'old_value' => 1 }; $VAR1 = 'After exiting the subroutine'; $VAR1 = { 'new_value' => 2, 'old_value' => 1 }; Section 3.8: Hashes Hashes can be understood as lookup-tables. You can access its contents by specifiying a key for each of them. Keys must be strings. If they're not, they will be converted to strings. If you give the hash simply a known key, it will serve you its value. # Elements are in (key, value, key, value) sequence my %inhabitants_of = ("London", 8674000, "Paris", 2244000); # You can save some typing and gain in clarity by using the "fat comma" # syntactical sugar. It behaves like a comma and quotes what's on the left. my %translations_of_hello = (spanish => 'Hola', german => 'Hallo', swedish => 'Hej'); In the following example, note the brackets and sigil: you access an element of %hash using $hash{key} because the value you want is a scalar. Some consider it good practice to quote the key while others find this style visually noisy. Quoting is only required for keys that could be mistaken for expressions like $hash{'some-key'} my $greeting = $translations_of_hello{'spanish'}; While Perl by default will try to use barewords as strings, + modifier can also be used to indicate to Perl that key should not be interpolated but executed with result of execution being used as a key: my %employee = ( name => 'John Doe', shift => 'night' ); # this example will print 'night'
GoalKicker.com – Perl® Notes for Professionals 13 print $employee{shift}; # but this one will execute [shift][1], extracting first element from @_, # and use result as a key print $employee{+shift}; Like with arrays, you can access multiple hash elements at the same time. This is called a hash slice. The resulting value is a list, so use the @ sigil: my @words = @translations_of_hello{'spanish', 'german'}; # ('Hola', 'Hallo') Iterate over the keys of an hash with keys keys will return items in a random order. Combine with sort if you wish. for my $lang (sort keys %translations_of_hello) { say $translations_of_hello{$lang}; } If you do not actually need the keys like in the previous example, values returns the hash's values directly: for my $translation (values %translations_of_hello) { say $translation; } You can also use a while loop with each to iterate over the hash. This way, you will get both the key and the value at the same time, without a separate value lookup. Its use is however discouraged, as each can break in mistifying ways. # DISCOURAGED while (my ($lang, $translation) = each %translations_of_hello) { say $translation; } Access to unset elements returns undef, not an error: my $italian = $translations_of_hello{'italian'}; # undef map and list flattening can be used to create hashes out of arrays. This is a popular way to create a 'set' of values, e.g. to quickly check whether a value is in @elems. This operation usually takes O(n) time (i.e. proportional to the number of elements) but can be done in constant time (O(1)) by turning the list into a hash: @elems = qw(x y x z t); my %set = map { $_ => 1 } @elems; # (x, 1, y, 1, t, 1) my $y_membership = $set{'y'}; # 1 my $w_membership = $set{'w'}; # undef This requires some explanation. The contents of @elems get read into a list, which is processed by map. map accepts a code block that gets called for each value of its input list; the value of the element is available for use in $_. Our code block returns two list elements for each input element: $_, the input element, and 1, just some value. Once you account for list flattening, the outcome is that map { $_ => 1 } @elems turns qw(x y x z t) into (x => 1, y => 1, x => 1, z => 1, t => 1). As those elements get assigned into the hash, odd elements become hash keys and even elements become hash values. When a key is specified multiple times in a list to be assigned to a hash, the last value wins. This effectively discards duplicates.
GoalKicker.com – Perl® Notes for Professionals 14 A faster way to turn a list into a hash uses assignment to a hash slice. It uses the x operator to multiply the single- element list (1) by the size of @elems, so there is a 1 value for each of the keys in the slice on the left hand side: @elems = qw(x y x z t); my %set; @set{@elems} = (1) x @elems; The following application of hashes also exploits the fact that hashes and lists can often be used interchangeably to implement named function args: sub hash_args { my %args = @_; my %defaults = (foo => 1, bar => 0); my %overrides = (__unsafe => 0); my %settings = (%defaults, %args, %overrides); } # This function can then be called like this: hash_args(foo => 5, bar => 3); # (foo => 5, bar => 3, __unsafe ==> 0) hash_args(); # (foo => 1, bar => 0, __unsafe ==> 0) hash_args(__unsafe => 1) # (foo => 1, bar => 0, __unsafe ==> 0) When used as booleans, hashes are true if they are not empty.
GoalKicker.com – Perl® Notes for Professionals 15 Chapter 4: Interpolation in Perl Section 4.1: What is interpolated Perl interpolates variable names: my $name = 'Paul'; print "Hello, $name!\n"; # Hello, Paul! my @char = ('a', 'b', 'c'); print "$char[1]\n"; # b my %map = (a => 125, b => 1080, c => 11); print "$map{a}\n"; # 125 Arrays may be interpolated as a whole, their elements are separated by spaces: my @char = ('a', 'b', 'c'); print "My chars are @char\n"; # My chars are a b c Perl does not interpolate hashes as a whole: my %map = (a => 125, b => 1080, c => 11); print "My map is %map\n"; # My map is %map and function calls (including constants): use constant { PI => '3.1415926' }; print "I like PI\n"; # I like PI print "I like " . PI . "\n"; # I like 3.1415926 Perl interpolates escape sequences starting with \: \t horizontal tab \n newline \r return \f form feed \b backspace \a alarm (bell) \e escape Interpolation of \n depends on the system where program is working: it will produce a newline character(s) according to the current system conventions. Perl does not interpolate \v, which means vertical tab in C and other languages. Character may be addressed using their codes: \x{1d11e} ???? by hexadecimal code \o{350436} ???? by octal code \N{U+1d11e} ???? by Unicode code point or Unicode names: