Perl Notes
Total Page:16
File Type:pdf, Size:1020Kb
Perl notes Curro Pérez Bernal <[email protected]> $Id: perl_notes.sgml,v 1.3 2011/12/12 15:41:58 curro Exp curro $ Abstract Short notes for an introduction to Perl based on R.L. Schwartz et al. Learning Perl (See refer- ences). Copyright Notice Copyright © 2011 by Curro Perez-Bernal <[email protected]> This document may used under the terms of the GNU General Public License version 3 or higher. (http://www.gnu.org/copyleft/gpl.html) i Contents 1 Scalar Data 1 1.1 Numbers..........................................1 1.1.1 Numeric Operators................................2 1.2 Strings...........................................2 1.2.1 String Operators.................................3 1.3 Scalar Variables......................................3 1.4 Basic Output with print ................................4 1.5 Operator Associativity and Precedence........................5 1.6 The if Control Structure.................................6 1.6.1 Comparison Operators..............................6 1.6.2 Using the if Control Structure.........................6 1.7 Getting User Input....................................7 1.8 The while Control Structure..............................8 1.9 The undef Value.....................................8 2 Lists and Arrays9 2.1 Defining and Accessing an Array............................9 2.1.1 List Literals.................................... 10 2.2 List Assignment...................................... 11 2.3 Interpolating Arrays................................... 11 2.4 Array Operators...................................... 12 2.4.1 Operators pop and push ............................ 12 2.4.2 Operators shift and unshift ........................ 12 2.4.3 The splice Operator.............................. 12 CONTENTS ii 2.4.4 The reverse Operator............................. 13 2.4.5 The sort Operator................................ 13 2.4.6 The each Operator................................ 13 2.4.7 Array clearing................................... 13 2.5 The foreach control structure............................. 14 2.5.1 Perl’s default scalar variable $_........................ 14 2.6 Scalar and List context.................................. 15 2.6.1 List-producing expressions in scalar context.................. 15 2.6.2 Scalar-producing expressions in list context.................. 16 2.6.3 STDIN in list context................................ 16 3 References 17 1 Chapter 1 Scalar Data The simplest kind of data in Perl are scalar data, that can be mostly numbers or strings of characters. 1.1 Numbers Both integers and floating-point numbers have an internal double-precision floating point rep- resentation. Examples of floating-point literals1 • 1.24 • 255.005 • 5.235E45 • -25.0E-11 • 251.0 • -1.9221 Examples of integer literals • 24 • 5 • 0 • -45 1A literal is how a particular value is represented in Perl. Chapter 1. Scalar Data 2 • -2501 • 19221 • 2519988585883 • 2_519_988_585_883 1.1.1 Numeric Operators • 2 + 4 • 5.6 - 34.4447 • 4.5 * 4 • -4 / 3 • 55.5 / 3 • 75 % 2 • 70 % 3 1.2 Strings Strings are character sequences that may contain any possible compination of characters. We may differentiate between single- and double-quoted string literals. Single-Quoted ’Markus’ ’Lena’ ’’ ’Shannon’ ’let\’s include an apostrophe!’ ’and a backslash: \\’ ’a backslash and n: \n’ Double-Quoted In this case the backslash is used to specify certain control characters. "Barbara" "Ana" "Hello Karen!\n" "Black\tWhile" Chapter 1. Scalar Data 3 The most important string backslash escapes are the following \a Beep \b Backspace \c "Control" caracter. \cD = CTRL-D \e Escape \f Form feed \l Make the next letter lowercase \n New line, return. \r Carriage return. \t Tab. \u Make the next letter uppercase \x Enables hex numbers \v Vertical tab \\ Print backslash \" Print double quotes \ Escape next character if known otherwise print. Also allows octal numbers. \L Make all letters lowercase until the \E \U Make all letters uppercase until the \E \Q Add a backslash-quote to all the nonalphanumerics until the \E \E Terminates the effects of \L, \U, or \Q \007 Any octal ASCII value \x7f Any hexadecimal value \cx Control-x 1.2.1 String Operators • “hello”.“world” • “GNU”.“/”.“Linux” • “This is”.“ ”.“a sentence.\n” • “Tuxie ” x 5 • 70 x 3 Perl performs the conversion between numbers and strings when it is necessary. 1.3 Scalar Variables Variables holding exactly one value that start with a $ (named the sigil) followed by a Perl identifier. All the variables that follow are different Chapter 1. Scalar Data 4 $hello $Hello $HELLO $Starting_Value $quite_long_variable_name It is important to select meaningful variable names, making use of underscores when possible2. The Perl assignment operator is the equals sign that takes a variable name in the left side that takes the value of the expression on the right. $hello = 5; $Hello = 4.33; $HELLO = "Good morning!\n"; $Starting_Value = $index - 3; $quite_long_variable_name = $x * 2; Binary assigments are shortcuts like the following $a = $a + 3; $a += 3; $a = $a * 3; $a *= 3; $string = $string." "; $string .= " "; 1.4 Basic Output with print print "This is a message for you.\n"; print "This is "; print "a message for you."; print "\n"; print "This is ", "a message for you."; print "The solution is ", 2*3.125,"\n"; Scalar variables in doubly-quoted string literals are subject to variable interpolation 2More valuable advices in the Perlstyle documentation. Chapter 1. Scalar Data 5 $op_sys = "GNU/Linux"; print "One of the best operating systems is $op_sys\n"; To print the dollar sign it has to be escaped or between single quotes print "The \$op_sys variable value is $op_sys\n"; print ’The \$op_sys variable value ’, "is $op_sys\n"; The variable name can be located between curly braces to prevent errors delimiting variable names $job = "student"; print "The book\’s owner is an $student\n"; print "This is the favourite bar of the college ${job}s\n"; 1.5 Operator Associativity and Precedence From the perlop documentation. Associativity Precedence (highest to lowest) left terms and list operators (leftward) left -> nonassoc ++ -- right ** right ! ~ \ and unary + and - left =~ !~ left * / % x left + - . left << >> nonassoc named unary operators nonassoc < > <= >= lt gt le ge nonassoc == != <=> eq ne cmp ~~ left & left | ^ left && left || // nonassoc .. ... right ?: right = += -= *= etc. left , => nonassoc list operators (rightward) right not left and left or xor Chapter 1. Scalar Data 6 In case of doubt: use parenthesis. 1.6 The if Control Structure 1.6.1 Comparison Operators Comparison operators return a true or false value and are the following Equal, numeric == Equal, string eq Not Equal, numeric != Not Equal, string ne Less than, numeric < Less than, string lt Less than or equal, numeric <=; Less than or equal, string leq Greater than, numeric > Greater than, string gt Greater than or equal, numeric >=; Greater than or equal, string geq Comparison, numeric <=> Comparison, string comp The unary not operator (!) give the opposite value of any Boolean value. 1.6.2 Using the if Control Structure The if control structure defines a block that only executed if its associated condition returns a true value if ($name gt "Monika") { print "’$name’ is after ’Monika’ in sort order\n"; } Chapter 1. Scalar Data 7 The keyword else allows an alternative choice if ($name gt "Monika") { print "’$name’ is after ’Monika’ in sort order\n"; } else { print "’$name’ is before ’Monika’ in sort order\n"; } You may use any scalar value in the conditional $value_1 = 10.0; $value_2 = 2; $check = $value_1 > $value_2; if ($check) { print "\$value_1 is larger than \$value_2\n"; } The rules for deciding if a value is true or false are the following: • All numbers are true except 0 (zero). • All strings are true besides the empty string (”). • All other cases are converted to a number or a string and the previous rules apply. 1.7 Getting User Input The simplest way to get a value from the keyboard into the program is the line-input operator, <STDIN>. Every time a program finds an <STDIN> where a scalar value is expected, Perl reads the next complete line from the standard input. The newline character at the end of the line can be removed using the chomp operator. $value_1 = 10.0; $value_2 = <STDIN>; print "\$value_2 = $value_2\n"; chomp($value_2); # newline is removed print "\$value_2 = $value_2\n"; $check = $value_1 > $value_2; if ($check) { print "\$value_1 is larger than \$value_2\n"; } This can be done in a single step Chapter 1. Scalar Data 8 $value_1 = 10.0; chomp($value_2 = <STDIN>); print "\$value_2 = $value_2\n"; $check = $value_1 > $value_2; if ($check) { print "\$value_1 is larger than \$value_2\n"; } 1.8 The while Control Structure This is one of the possible control structures in Perl. It repeats a block of code as long as a given condition is accomplished: $counter = 10; while ($counter > 0) { print "\$counter = $counter\n"; $counter -= 2; } The conditional is evaluated prior to the first iteration, thus it is possible that the block is not executed a single time if the condition is initially false. 1.9 The undef Value Values used before being assigned take the special value undef. If it is expected to take a numerical value then the assigned value is zero, while in a string value the variable takes the empty string value. This is a standard behavior, though Perl will usally warn the user when unusual uses of the undef value occur. 9 Chapter 2 Lists and Arrays A list is defined as an ordered collection of scalars, and an