Link | Description | Commands used |
Perl invocation | How perl is called from the shell | perl scriptname |
Perl Script template | Basic file for creating perl secripts | template.pl |
Scalar Variables | Numbers and Strings, expressions, Naming Convention, examples | $var = value; chop(), chomp(), print() |
Conditional Control Structure | if syntax, examples | if (expr) { expr true block } |
Comparison Operators | List of numerical & string Operators | |
Other if variants | if-else, if-elsif-else syntax, examples, conditional expressions | if (expr) { expr true block } else { expr false block } if (expr) { expr true block } elsif (expr2) { expr2 true block } ... else { all exprs false block } |
Iterative Control Structure | while, until syntax, examples, conditional expressions |
while (expr) { expr true block } until (expr) { expr false block } |
debugging 1 | A debugging exercise | |
Scalar Data | Numbers and Strings, examples,Symbolic Formats | |
debugging 2 | Another debugging exercise | |
Operator Precedence Table | Operator Precedence and associativity | |
Scalars and Literals | More on Scalar Data |
1. Perl=Practical Extraction and Report Language by Larry Wall o Sits within C Language and Shell, awk and sed programs o Adaptable to mixed languages: sql, tk/tcl, C o Is network aware o System Administrators Tool 2. Selected Command line Options: $ /usr/bin/perl [-cdnpvw] [-Dlist] [-e commandline (one per -e)] -c Causes Perl to check the syntax of the script and then exit without executing it. -d Runs the script under the Perl debugger. See the perldebug manpage. -n Assumes an input loop about your script. Lines are not printed (like awk or sed -n) -p Assumes an input loop about your script. Lines are not printed (like awk or sed -n) -v prints the version and patchlevel of your Perl executable. -w prints warnings about identifiers that are mentioned only once, and scalar variables that are used before being set. Also warns about redefined subroutines, and references to undefined filehandles or filehandles opened readonly that you are attempting to write on. Also warns you if you use values as a number that doesn't look like numbers, using a an array as though it were a scalar, if your subroutines recurse more than100 deep, and innumeriable other things. See the perldiag manpage and the perltrap manpage. -Dlist Sets debugging flags. To watch how it executes your script, use -D14. (This only works if debugging is compiled into your Perl.) Another nice value is -D1024, which lists your compiled syntax tree. And -D512 displays compiled regular expressions. As an alternative specify a list of letters instead of numbers (e.g. -D14 is equivalent to -Dtls): 1 p Tokenizing and Parsing 2 s Stack Snapshots 4 l Label Stack Processing 8 t Trace Execution 16 o Operator Node Construction 32 c String/Numeric Conversions 64 P Print Preprocessor Command for -P 128 m Memory Allocation 256 f Format Processing 512 r Regular Expression Parsing 1024 x Syntax Tree Dump 2048 u Tainting Checks 4096 L Memory Leaks (not supported anymore) 8192 H Hash Dump -- usurps values() 16384 X Scratchpad Allocation 32768 D Cleaning Up -e cmd May be used to enter one line of script. If -e is given, Perl will not look for a script filename in the argument list. Multiple -e commands may be given to build up a multi-line script. Make sure to use semicolons where you would in a normal program. 3. Template and Sample Program $ cat template.pl #! /usr/bin/perl $USAGE = "program1.perl"; # Author: Robert Katz # Date: January 6, 2000 # Purpose: This is a template for writing perl scripts # Your commands go under this line. # END OF template.pl Be sure to make this program executable and then use it to copy from. Sample Program: $ cat program1.perl #! /usr/bin/perl # This program reads a line of input and writes the line back out. $USAGE = "program1.perl"; $inputline = <STDIN>; # Read a line of input print ( $inputline ); # END OF program1.perl $ program1.perl This is a line of input. This is a line of input. 4. Statement Rules (1) Language Tokens (e.g. $inputline, = , <STDIN>, ; ) must have at least 1 instance of whitespace in between. (2) New statements always start on a new line. (3) Comments are signified by starting with a # and ending with a newline. 5. $inputline is a scalar (one valued) variable = is an assignment operator <STDIN> represents 1 line of input from the Standard input file ; is an statement terminator print is a library function that sends data to the Standard output file ( also known as <STDOUT> in perl ) 6. Scalar Variable Syntax $ followed by at least one upper or lower case letter, which is then followed by any number of upper or lower case letters, digits, or _ 7. Definition Examples using arithmetic operators (+ - * / ): $var = 12; $var = 103; $name = "input data"; $var = 17 + 12; # implies $var = 29 $var1 = 17 + 5 - 3; # implies $var1 = 19 $var2 = $var1 * 6; # implies $var2 = 114 $var3 = $var2 / $var1; # implies $var3 = 6 $var4 = 6 + 2 * 4; # implies $var4 = 14 Multiplying first! 8. Program to convert Miles to Kilometers $ cat program2.perl #! /usr/bin/perl # This program processes a unitless distance as miles and kilometers. $USAGE = "program2.perl"; print ( "Enter the distance to be converted: \n"); $originaldist = <STDIN>; # Read a distance value chop ($originaldist); # delete final newline character $miles = $originaldist * 0.6214; $kilometers = $originaldist * 1.609; print ( $originaldist, " kilometers = ", $miles, " miles \n" ); print ( $originaldist, " miles = ", $kilometers, " kilometers \n" ); # END OF program2.perl $ program2.perl Enter the distance to be converted: 10 10 kilometers = 6.214 miles 10 miles = 16.09 kilometers 9. The chop (and chomp) library functions chop list Deletes the last character (usually a newline, if input) on all the elements of the list. Return value is the chopped character. chomp list Remove line endings from all the elements of the list. Return value is the total number of characters removed. 10. Perl Expressions A Perl Expression is a collection of operators and operands. Each expression yields a result, which is the value you get when the Perl interpreter evaluates the expression by performing the specified operations. An expression and a statement are different. A statement may contain a perl expression. Example: statement (has a semi-colon) ($var = 4 * 5 + 3); #1. subexpression 4 * 5 evaluates to 20 ($var=20 + 3); #2. subexpression 20 + 3 evaluates to 23 ($var=23); #3. subexpression var=23 evaluates to result 23 and assigned to var ($var1 = $var2 = 42; ); #1. subexpression var2=42 evaluates to result 42 and assigned to var2 ($var1 = 42; ); #2. subexpression var1=42 evaluates to result 42 and assigned to var1 11. Conditional Statements: if Format: if (conditional expression) { statement block when true } - Braces are required! - Statement block can be null (not useful but legal) - if the conditional expression evaluates to non-zero, it returns true and executes the statement block. Otherwise, if the expression evaluates to zero, it returns false and control goes to the line after the close brace. 12. Example: $ cat program3.perl #! /usr/bin/perl # This program exercises the simple if statement. $USAGE = "program3.perl"; print ( "Enter a number: \n"); $number = <STDIN>; # Read a number chop ($number); # delete final newline character if ($number) { print ("The number is not zero. \n"); } print ( "This is the last output of the program.\n" ); # END OF program3.perl $ program3.perl Enter a number: 5 The number is not zero. This is the last output of the program. $ 13. Comparison Operators: (all return true or false except <=> and cmp) equality comparison operator == inequality comparison operator != string equality comparison operator eq string inequality comparison operator ne Less than comparison operator < greater than comparison operator > string less than comparison operator lt string greater than comparison operator gt Less than/equal comparison operator <= greater than/equal comparison operator >= string less than/equal comparison operator le string greater than/equal comparison operator ge numerical comparison operator <=> returns -1,0,1 string comparison operator cmp returns -1,0,1 14. Other variants: if - else Format: if (conditional expression) { statement block 1 wben true } else { statement block 2 when not true } 15. Example: $ cat program4.perl #! /usr/bin/perl # This program exercises the if-else statement. $USAGE = "program4.perl"; print ( "Enter a number: \n"); $number1 = <STDIN>; # Read first number chop ($number1); # delete final newline character print ( "Enter another number: \n"); $number2 = <STDIN>; # Read second number chop ($number2); # delete final newline character if ($number1 == $number2) { print ("The two numbers are the same. \n") } else { print ("The two numbers are different. \n") } print ( "This is the last output of the program.\n" ); # END OF program4.perl $ program4.perl Enter a number: 5 Enter another number: 17 The two numbers are different. This is the last output of the program. $ 16. Other variants: if - elsif - else Format: if (conditional expression 1) { statement block 1 wben true } elsif (conditional expression 2) { statement block 2 when true } elsif (conditional expression 3) { statement block 3 when true ... } [ else { statement block 4 when all false } ] 17. Example: $ cat program5.perl #! /usr/bin/perl # This program exercises the if - elsif - else statement. $USAGE = "program5.perl"; print ( "Enter a number: \n"); $number1 = <STDIN>; # Read first number chop ($number1); # delete final newline character print ( "Enter another number: \n"); $number2 = <STDIN>; # Read second number chop ($number2); # delete final newline character if ($number1 == $number2) { print ("The two numbers are the same. \n") } elsif ($number1 == $number2 + 1) { print ("The first number is greater by one. \n") } elsif ($number1 + 1 == $number2) { print ("The second number is greater by one. \n") } else { print ("The two numbers are different. \n") } print ( "This is the last output of the program.\n" ); # END OF program5.perl $ program5.perl Enter a number: 16 Enter another number: 17 The second number is greater by one. This is the last output of the program. 18. Iteration Statements: while Format: while (conditional expression) { statement block when true } - Braces are required! - Statement block can be null (not useful but legal) - if the conditional expression evaluates to non-zero, it returns true and executes the statement block. When execution is complete, it jumps back to the conditional expression and reevaluates it. Otherwise, if the expression evaluates to zero, it returns false and control goes to the line after the close brace. 19. Example: $ cat program6.perl #! /usr/bin/perl # This program exercises the while statement. $USAGE = "program6.perl"; $done = 0; $count = 1; print ( "This line is printed before the loop starts. \n"); while ($done == 0) { print ("The value of count is", $count, "\n"); if ($count == 3) { $done = 1; } $count = $count + 1; } print ( "Beyond the end of the loop.\n" ); # END OF program6.perl $ program6.perl This line is printed before the loop starts. The value of count is 1 The value of count is 2 The value of count is 3 Beyond the end of the loop. 20. Iteration Statements: until Format: until (conditional expression) { statement block when false } - Braces are required! - Statement block can be null (not useful but legal) - if the conditional expression evaluates to zero, it returns false and executes the statement block. When execution is complete, it jumps back to the conditional expression and reevaluates it. Otherwise, if the expression evaluates to non-zero, it returns true and control goes to the line after the close brace. 21. Example: $ cat program7.perl #! /usr/bin/perl # This program exercises the while statement. $USAGE = "program7.perl"; print ( "What is 17 times 26? \n"); $correct_answer = 442; $input_answer = <STDIN>; chop ($input_answer); until ($input_answer == $correct_answer) { print ("Wrong! Keep trying! \n"); $input_answer = <STDIN>; chop ($input_answer); } print ( "You got it! \n" ); # END OF program7.perl $ program7.perl What is 17 times 26? 43 Wrong! Keep trying! -9 Wrong! Keep trying! 442 You got it! 22. Debugging Corner: What's wrong here? #! /usr/bin/perl $value = <STDIN>; if ($value = 17) { print ("You typed the number 17. \n"); else { print ("You did not type the number 17. \n"); } --------------------------------------------------------------------------- #! /usr/bin/perl # program which prints the next five numbers after # the number typed in. $input = <STDIN>; chop ($input); $input = $input + 1 # start with next number $input = $stop + 5 # and loop 5 times until ($input == $stop) { print ("The next number is ", $stop, "\n"); } 23. Scalar Values (one unit of number or string data) Integer constants (Integer literals) = 1 or more digits, optionally with a minus sign 14 10000000000 -27 $x = 12345; $x = 012345; # Octal integer if leading 0 $x = 0x12345; # Hexadecimal integer if leading 0x 24. Example $ cat program8.perl #! /usr/bin/perl # This program exercises the integer limits. $USAGE = "program8.perl"; $value = 1234567890; print ("First value is ", $value, "\n"); $value = 1234567890123456; print ("Second value is ", $value, "\n"); $value = 12345678901234567890; print ("Third value is ", $value, "\n"); # END OF program8.perl $ program8.perl First value is 1234567890 Second value is 1.23456789012346e+15 Third value is 1.23456789012346e+19 25. Scalar Values (one unit of number or string data) Floating point values = 1 or more digits, optionally with a minus sign, decimal point, and/or a power of 10 exponent (denoted e or E) followed by an optionally signed 1 to 3 digit integer 11.4 -0.314 +275.0 .3 3. 8e+01 e-01 5.12e0 5.47e3 26. Example $ cat program9.perl #! /usr/bin/perl # This program exercises the integer limits. $USAGE = "program9.perl"; $value = 34.0; print ("First value is ", $value, "\n"); $value = 114.6e-01; print ("Second value is ", $value, "\n"); $value = 178.263e+19; print ("Third value is ", $value, "\n"); $value = 12345678901234567890000000000000000000000; print ("Fourth value is ", $value, "\n"); $value = 1.23e999; print ("Fifth value is ", $value, "\n"); $value = 1.23e-999; print ("Sixth value is ", $value, "\n"); # END OF program9.perl $ program9.perl First value is 34 Second value is 11.46 Third value is 1.78263e+21 Fourth value is 1.23456789012346e+40 Fifth value is Infinity Sixth value is 0 27. Scalar Values (one unit of number or string data) text = 1 or more characters in a string consisting letters, digits, spaces and/or special characters Literal string via single quotes. (\' and \\ can be processed) Equivalent is: q/abc/ to 'abc' Scalar variable substitution is supported via double quotes. equivalent is: qq/abc/ to "abc" $number = 11; $text = "This text contains the number $number."; Undefined variables are assumed to be initialized as Null. Escape Sequences: \a Bell \b Backspace \cn The <Ctrl+n> Character \e Escape (del next char) \f Form feed \l Next letter to lowercase \L Rest lowercase \n Newline \r Carriage Return \t tab \u Next letter to uppercase \U Rest Uppercase \v Vertical tab \033 Octal (\nnn) \x1b Hexadecimal (\xnn) /E Escape: Ends a /L, /U or /Q \Q adds \ to end of each word $a = "T\LHIS IS A \ESTRING"; # same as "This is a STRING" $result = 14; print ("The value of \$result is $result. \n"); yields: The value of $result is 14. 28. Examples $ cat program10.perl #! /usr/bin/perl # This program exercises the Escape sequences. $USAGE = "program10.perl"; print ("Enter a line of input: \n"); $inputline = <STDIN>; print ("uppercase: \U$inputline\E\n"); print ("lowercase: \L$inputline\E\n"); print ("as a sentence: \L\u$inputline\E\n"); # END OF program10.perl $ program10.perl uppercase: THIS IS IN LOWERCASE. lowercase: this is in lowercase. as a sentence: This is in lowercase. $ cat program11.perl #! /usr/bin/perl # This program exercises the conversion of numbers and strings. $USAGE = "program11.perl"; $text = "This is a string on two lines"; print ("text value is $text \n"); $string = "43"; $number = 28; $result = $string + $number; print ("43 + 28 result is $result \n"); print ("Enter a number "); $number = <STDIN>; chop ($number); $result = $number + 2; print ("input + 2 result is $result \n"); $result = "hello" + 5; # "hello" converted to 0 print ("hello and 5 result is $result \n"); $result = "0xff" + 1; # "0xff" converted to 0, 1.9921875, 255 print ("hex 255 and 1 result is $result \n"); $result = "12O34" - 1; # "12"oh"34" converted to 12 print ("12O34 less 1 result is $result \n"); # END OF program11.perl $ program11.perl # run on HPUX Perl 5.004 text value is This is a string on two lines 43 + 28 result is 71 Enter a number 23 input + 2 result is 25 hello and 5 result is 5 hex 255 and 1 result is 1 12O34 less 1 result is 11 29. Debugging Corner: What's wrong here? #! /usr/bin/perl $inputline = <STDIN>; print ('here is the value of \$inputline\', ": $inputline"); -------------------------------------------------------------------------------- #! /usr/bin/perl $num1 = 6.02e+23; $num2 = 11.4; $num3 = 5.181e+22; $num4 = -2.5; $result = $num1 + $num2 + $num3 + $num4; -------------------------------------------------------------------------------- #! /usr/bin/perl $result = "26" + "0xce" + "1"; 30. More Operators
Operator | Meaning | Example |
++ -- | Auto increment, Auto decrement | $x=5; print (++$x) 6 $x=5; print (--$x) 4 |
-> | Dereference Operator | var[28] = 3; p -> [28]; (29th element reference by $p) |
\ | Unary reference Operator | $p = \@var (p is a reference to array @var equivalent to $$p[28]) |
- ~ ! | Unary minus, bitwise Unary complement, Unary Negation | -14 ~14 = -15 ! 0 = 1 |
** | Exponentiation | 3 ** 3 = 27 2 ** -5 = 0.03125 5 ** 2.5 = 55.9016994374947 |
=~, !~ | Pattern matches; contains or doesn't | $a = 1; $a =~ /please/ $a = 1; $a !~ /thanks/ |
* / % x | Multiply, Divide, Remainder, Repetition | 3 * 3 = 9 7 / 2 = 3.5 7 % 2 = 1 7 x 3 = 777 |
+ - . | Addition, Subtraction,concatenation | "3a"."3b" = "3a3b" |
<< >> | Shift left, Shift right | 36 >> 2 = 9 36 >> 2 = 144 |
-e -r -w -x -o -s -f -d -l -S -p -b -u -g -k -c -t -T -B -M -A -C |
File Test Operators (zero, readable, writable, executable, owned by uid, file type, setuid,setgid,sticky, interactive tty, Text or Binary file, modification, access, inode change time) |
if ( -e "file1") { print file1 exists; } else { print file1 nonexistent; } |
<, <=, >, >=, lt, le, gt, ge |
Inequality Comparison operators | 1 < 2; 2 > 1 |
==, !=, <=>, eq, ne, cmp |
Equality Comparison operators | 3 == 3; 2 != 3; $y = $x <=> 10; print $y; #one of -1, 0, 1 is output |
& | Bitwise "and" | 15 & 7 = 7; |
|, ^ | Bitwise "inclusive or", "exclusive or" | 15 | 7 = 15; 15 ^ 7 = 8 |
&& | Logical "and" | $a && $b #true if both non-zero else false |
|| | Logical "or" | $a || $b #true if either non-zero else false |
.. | List range operator | (1..10) # list of integers 1 thru 10 inclusive |
? : | Conditional operator | $r = $a == 0 ? 14 : 7; # (r=14 if a==0 is true else r=7) |
= | Assignment operator | $a = 4; |
**= | Compound assignment operators | $a **= 4; # a gets result of $a to 4th power |
*=, /=, %= | Compound assignment operators | $a *= 4; # a gets result of 4*$a |
+=, -= | Compound assignment operators | $a += 4; # a gets result of 4 + $a |
&=, |=, ^=, | Compound assignment bitwise operators | $a = 15; $a &= 7; a gets result of 15 && 7 = 7 |
>>=, <<=, | Compound assignment shift operators |
|
&&=, ||=, | Compound assignment logical operators |
|
.=, x= | Compound assignment concatenation, repetition operators |
|
, | Comma operator | $val = 26; $r = (++$val, $val + 5); # r gets 32 via 26 to 27 to 32 |
Questions? Robert Katz: katz@cis.highline.ctc.edu