image001

Home

Syllabus

Notes

Homework


Perl in a Lecture

Full notes FYI


Perl
        Data types
        Scalar Data
        Conversion between strings and numbers
        Numerical operators
        String operators
        Chop and chomp
        Print, printf, and sprintf

        Lists
        Arrays
        Control Structures
        Associative Arrays (Hashes)
        Basic I/O
        Regular Expressions
        Functions
        Misc. Control Structures
        Files

Losing your (programming language) innocence: 4 ways of doing the same thing in Perl


Data types

  • Perl has essentially three data types
    • Scalars
    • Arrays
    • Associative Arrays
  • (There are others, but we won't worry about them here.)

Scalar Data

  • A scalar is essentially anything that is a single item
  • Like with awk, whether it's a number or a string is determined by context
  • Numbers
    • Can be an integer or a floating-point number
    • You don't need to worry about how Perl stores the numbers, unless you base a decision on whether 10/3 is the same as 10*(1/3), because it isn't.
      1. Code to show this: perl/p0. Note: Perl will not truncate to integers, I mis-spoke, but roundoff errors can confuse you ..
    • Numbers can be specified as literals (the number itself appears in the program) in any of the following formats:
 
        150
        -40        # the temperature where farenheit and celsius match
        2.13
        3.8e22     # 3.8 times 10 to the 22nd power
        5.8735e-43 # a very tiny number!
    • One warning: Don't start a number with a zero, like "041", because, like C, Perl interprets that to mean an octal number, which in this case would be 33.
    • "0x" indicates hexadecimal numbers. (0x21 is 33)
  • Strings
    • Any number of ASCII characters (up to the limits of your computer's memory).
    • "NUL" is not special, like it is in C.
    • You don't need to allocate memory for your string, like you do in C.
    • Literal strings can be "single-quoted strings", "double-quoted strings," or "here documents" (which we'll cover later).
    • Single-quoted and double-quoted strings work just like we've seen before
    • "Here documents" are a form of double-quoted string
    • Special characters in double-quoted strings
 
        \n      # Newline
        \t      # Tab
        \\      # Backslash
        \"      # Double quote
 
        \r      # Carriage Return
        \f      # Formfeed
        \b      # Backspace
        \a      # Bell
        \e      # Escape
        \0nn    # An octal value
        \xnn    # A hexadecimal value
        \cC     # A control character (control-C here)
        \l      # Make next letter lower-case
        \L      # Make everything lower-case until \E
        \u      # Make next letter upper-case
        \U      # Make everything upper-case until \E
        \Q      # Backslash-quote all nonalphanumeric characters until \E
        \E      # Terminate \L, \U, or \Q
  • Scalar variables
    • A scalar variable is specified by a dollar sign ($), followed by a letter, followed (possibly) by more letters, digits, or underscores.
    • Limit is 256 characters.
    • Case is significant. ($linelength is a different variable than $lineLength)
    • Before a variable has anything assigned to it (and in a few other instances) it has the value undef.
      • If used as a number undef is a 0; if used as a string, it is "". But it really is a distinct value.
  • Assignment
    • Like in C, assignment is indicated with an equal sign (=).
    • Ex: $total = $score1 + $score2 + $score3
    • The value of an assignment is the value assigned, so you can use an assignment in an expression
    • Examples: $b = 4 + ($a = 3) or (possibly more useful) $a = $b = $c = 3

Conversion between strings and numbers

  • Perl automatically converts between strings and numbers, as needed.
  • In string-to-number conversion, any numbers in the string will be used.
  • If no numbers are in the string, its numeric value is 0.
  • Numbers are converted to strings just as they would be in a "print" statement.
  • If you use the "-w" flag with Perl, (i.e. put "#!/usr/local/bin/perl -w" at the start of your script), Perl will warn you about "weird" conversions
  • By the way, it's a really good idea to use the "-w" flag, it can catch a lot of problems.

Numerical operators

  • Basic
    • + (Addition)
    • - (Subtraction)
    • * (Multiplication)
    • / (Division)
    • ** (Exponentiation. e.g. 2**3 == 8)
    • % (Modulus. e.g. 10%3 == 1)
  • Numerical comparison operators
    • == (equal)
    • != (Not equal)
    • <= (Less than or equal)
    • < (Less than)
    • >= (Greater than or equal)
    • > (Greater than)

String operators [Skipping]

Chop and chomp [Skipping]

Print, printf, and sprint [Skipping]

Lists

  • A list is an ordered collection of scalar data (used to assign to an array, which is covered next)
  • Represented in a program by several values, separated by commas and enclosed by parentheses
  • Strings and numbers can be mixed in a list
  • Example: (1, 2, "three", "four", 5)
  • The empty list is represented by a pair of empty parentheses ()
  • The list constructor operator can represent a sequence of numbers (1 .. 5) is the same as (1, 2, 3, 4, 5)
    • If the right value is less than the left value, the resulting list is the empty list
    • If the values are not whole numbers, the intervening values are still one greater than the starting value
    • If the "final" number is not an integer greater than the first value, the last "good" value is the value of the list
    • The list (1.2 .. 5.1) is really (1.2, 2.2, 3.2, 4.2)
  • If the list consists solely of strings, the "qw" (quote words) fuction can be used to simplify the representation
  • Example: ("eenie", "meenie", "minie", "moe") can be qw(eenie, meenie, minie, moe)

Arrays

  • An array is a variable that holds a list
  • Named like a scalar variable, but using @ instead of $
  • @something and $something are completely different variables
  • An array can be assigned a list, or another array
  • Example: @array = (1, 2, 3); @array2 = @array;
  • A list can contain an array. The array members are simply inserted into the list
    • Example: @array = (3, 4, 5); @array2 = (1, 2, @array, 6); results in @array2 being the list (1, 2, 3, 4, 5, 6)
    • If an array is used in a scalar context, the scalar value is the number of elements in the list
    • Example: @array = (3, 4, 5); $array = @array; results in $array being 3 (oops: another way to do this)
  • A list of variables can appear on the left-hand side of an assignment
    • Example: ($one,$two,$three) = (1, 2, 3);
  • Array elements
    • Array elements are accessed by a subscript in square brackets []
    • The index of the first element is 0
      • Example: If an array is @array = qw(one, two, three) then $array[0] is "one", $array[1] is "two" and $array[2] is "three"
      • This is the same as C, different than awk
    • Note that the array element starts with a $, since it's a scalar value
    • An array slice is more than one value from the same array, and since it's a list, the @ is used (Example: @array[0,1] is the first two elements of @array)
    • The index in an array can be a variable (useful in loops, for example)
    • If you access an element outside the bounds of the array, you get the undef value
      • Much nicer than C, which gives you a core dump if you do that
    • Assigning to an element outside the bounds of the array automatically extends the array (and assigns any intervening values to undef)
      • Again, much nicer than the core dump C would give you
    • The last index in an array is represented by $#arrayname
      • Example: @array = (1,2,3), $#array is 2
      • You can assign to $#arrayname to grow or shrink an array, but usually don't need to, since the array grows and shrinks automatically, as needed
    • A negative subscript counts from the end, so $array[-2] is the second to last element of @array
    • Example: perl/p2a
  • Push and pop
    • Arrays can be treated like stacks with the push and pop functions
    • push appends a scalar (or a list) to the end of an array
    • pop takes an element off the end of an array
    • Example
 
        @array = (1);
        push (@array, 2);
        push (@array, 3, 4, 5);
        $var = pop (@array);
    •             See example: perl/p2b
    • push also happens to be a handy way to add values to an array, even if you aren't using the array as a stack
  • Shift and unshift
    • Like pop and push, but at the beginning rather than the end of the list
  • Reverse
    • Returns a list that contains the elements of its argument, in reverse order
    • Example
 
        @array = (1, 2, 3, 4);
        @revarray = reverse (@array);
  • Sort
    • Returns a list containing the elements of its argument, in sorted order
    • Default order is ASCII order, but you can specify your own order (we won't worry about this right now)
  • Chomp on an array
    • When used on an array, chomp chomps each element of the array

Control Structures [Skipping]

Associative Arrays (Hashes)

  • Hashes
    • Also called "associative arrays," though hash has become the more popular term (no doubt because it's shorter).
    • Unlike arrays, hashes have no particular order.
    • Represented as variables with a %, as in %some_hash.
    • The values of a hash are key/value pairs, referenced with curly braces
    • The key is automatically quoted
    • Example:
 
        $salary{Joe} = 40000;
        $salary{Sherry} = 60000;
        $salary{Sam} = 20000;
    • A hash has no literal representation. It is represented as an array, with the first value as a key, then a value, then a key, then a value, etc.
    • Example:
 
        %salary = ("Joe", 40000, "Sherry", 60000, "Sam", 20000);
        if ( $salary{Sam} <= $salary{Joe} ) {print "Sam is underpaid!\n";}
    • The token "=>" is just a synonym for ",", but makes hash declarations look much better
    • Example:
 
        %salary = (
                Joe    => 40000,
                Sherry => 60000,
                Sam    => 20000,
        );
    • Note that "=>" causes the item to its left to be quoted, so you don't need the quotes
  • keys function
    • Returns the keys of a hash, as a list
    • Returns an empty list if the hash is empty
    • Useful for iterating through the hash
    • Example:
 
        foreach $employee (keys (%salary)) {
                print "$employee makes $salary{$employee}.\n";
        }
  • values function
    • Like keys, but returns the values of the hash
  • each function
    • Returns a two-element list, containing a key/value pair from a hash
    • On each successive call, returns another key/value pair
    • Returns an empty list (hence false) when there are no more key/value pairs
    • Example:
 
        while ( ($employee, $salary) = each (%salary) ) {
                print "$employee makes $salary.\n";
        }
  • delete function
    • Removes a value from a hash
    • Example: delete $salary{Joe}; #Joe quit
  • Hash slices
    • A shorthand way to specify part of a hash
    • Example:
 
        @salary{Joe,Sherry,Sam} = (40000, 60000, 20000);

Basic I/O [Skipping]

Regular Expressions [Skipping]

Functions [Skipping]

Misc. Control Structures [Skipping]

Files [Skipping]

Losing your (programming language) innocence: 4 days of doing the same thing in Perl

[This is from the 2011 final exam; note we spent 3-4 lectures on perl so I won’t test you nearly this deep this year!]

. [12 points] Give 4 ways in perl  the following key/value pairs representing test scores into an associative array  (you may name the array anything that matches perl conventions/rules for an associative arrway).

 

Key

Value

JoeVandal

50

ButchTheCoug

100

WhitepawTheMalmute

0

 

 

(Um, obviously these can come in any order.  And “score” can be any variable name.)

#1

$score{JoeVandal}=50;

$score{ButchTheCoug}=100;

$score{WhitepawTheMalmute}=0;

 

 

#2

%score={“JoeVandal”,50,”ButchTheCoug”,100,”WhitepawTheMalmute”,0};

 

 

#3

%score = (

                        JoeVandal => 50,

                        ButchTheCoug => 100,

                        WhitepawTheMalmute => 0,

            );

 

 

#4 @score{JoeVandal,ButchTheCoug,WhitepawTheMalmute} = (50,100,0);