Perl: Lecture 1 notes

(as taken by Deb Deppeler on 2/3/3)

Announcements

  1. Instructor: Sharon Whiteman (whiteman@cs.wisc.edu)
  2. Link to web page at:  http://www.cs.wisc.edu/~whiteman
  3. Next class will meet from 5:30-6:30pm in 1325CS
  4. Assume students are familiar with high-level programming languages and UNIX.

Intro

Perl is an amazing scripting language for parsing text files.  There are a lot of different ways to write the same program in Perl.

How do I write a Perl Program?

  1. Open favorite UNIX editor with desired file name.  Sharon uses vi.  Current naming convention is a single word (no spaces allowed) for the file without an extension.  (i.e.  example1 )
  2. Type  a shebang as the first line of your Perl program.
    #!/usr/bin/perl

    To get warning regarding "bad" things you do.  This should be used during development of your Perl scripts.
    #!/usr/bin/perl -w
  3. Type the use statements, if any are required. These are similar to #include and import statements.  They tell what other libraries (modules) will be used by this program.   Note: There is also a require that has a similar purpose.  It has a different implementation.
  4. Start programming.  There is no main function or method.  It's implicit.

Note:  All vars are global by default.   There are ways around this that we'll learn later.

How do I run my Perl Program?

  1. Save and close file.   Close editor or open a new xterm window to the same directory.
  2. Change the file permissions so that the program is executable.
    nova1% chmod +x example1
    nova1% chmod 700 example1
  3. Type the name of the program and press Enter.
    nova1% example1

Comments

All comments in Perl start with the # character and continue to the end of the line.  There are no multi-line comments in Perl.

Scalar Data

There is no concept of int, float, char, String, etc. in Perl.  Perl will type cast all data internally.  (It usually gets this right.)   All scalar data variables start with a $ character.

Numbers

Numbers are all considered double precision floating point.

$x = 5;        # assigns value 5 to variable $x
               # default value is 'undef'

$x = 5.5;      # assigns value 5.5 to variable $x
$x = 5e-3      # assigns 5.0 x 10-3 to variable $x

Arithmetic Operators:   +    -    *    /     %

Arithmetic operations are the same in Perl as in C/C++/Java, except for the % operator.  Arithmetic operations follow the standard precedence rules for evaluating expressions.

The mod operator %

The mod operator % will accept floating point values, truncate them, divide them and return the remainder of that division.  For example,   10 % 3 = 1, but so does 10.6 % 3.2 = 1

Example Program

#!/usr/bin/perl
$x = 3;
$y = 4;
$x = $x + $y;
print $z;          # output value of $z, which is 7

Strings

All character strings are still scalar data in Perl.  Strings are not null-terminated.  There is theoretically no limit to the length that a string can be in Perl.  Of course, filling memory with a single string value would mean that nothing else could be completed.

Literal strings are enclosed in single quotes.

$cat = 'meow'; # assigns the string of characters 'meow' to the variable $cat
$dog = 'woof'; # assigns the string of characters 'woof' to the variable $dog

What's the difference between single and double quotes?

Single quotes are used for literal strings.  Double quotes are used when you want evaluate the contents of the string of characters (as variable names).

Example
$animals = '$cat'; # $animals contains '$cat'
$animals = "$cat"; # $animals contains 'meow' (the contents of the variable $cat)

String Operations

  Examples
Concatenation
$animals = $cat . $dog;     # meowwoof
$animals = "$cat" . "$dog"; # meowwoof
$animals = "$cat . $dog";   # meow.woof
$test = "$animals";         # meowwoof
Repetition
$cat = 'meow' x 3;          # meowmeowmeow
Auto conversion to numbers
$x = '3';       # converted to a number for arithmetic
$y = 4;         # stored as a number
$z = $x + $y;   # $z equals value 7
$x = '123fred'; # converted to 123 for arithmetic
$y = 'fred4';   # converted to 4 for arithmetic
$z = $x + $y;   # 127 (from 123 + 4)

Boolean

The boolean values true and false are also scalars.

Print to Standard OUTPUT

print $cat;          # prints meow
print "$cat";        # prints meow
print '$cat';        # prints $cat
print $cat . $dog    # prints meowwoof
print "$cat . $dog"  # prints meow . woof     NOT SURE ???  TRY ON YOUR OWN
print "$cat\t$dog";  # prints meow    woof
print "\"";          # prints "

Comparison

To compare numbers: ==   !=    <   >  <=   >=
To compare strings: eq   ne   lt  gt  le   ge

if statements

# Selection using comparison operations
if ($x == 0)
{                           # MUST use braces for blocks
     # stmts here           # value 0 is false
                            # value '0' is false
                            # value \000 is false
                            # value undef is false
}                           # Note: NO semi-colon

# Selection using scalar boolean values
if (true)                   # booleans are Scalar
{
    # stmts
}

# if-elsif-else
if ( cond )
{
    # stmts
}
elsif ( cond )     # note spelling
{
    # stmts
}
else
{
    # stmts
}

# Remaining conditional to try in Perl
if (undef == undef)
{
    # stmts
}

while loop

while ($x < 1)
{
    $x++;           # ++$x;  "Does this work???   NOT SURE"
}

INPUT

No scanf, cin, system.in, etc.

$line = <STDIN> ;   # assigns user input to $line

Sample Program

#!/usr/bin/perl -w
# Get user's name
print "Name: ";
$inputName = <STDIN>;
chomp $inputName;

# Get user's height
print 'Input height: ';
$inputH = <STDIN>;
chomp $inputH;

# Calculate height
$heightCM = $inputH * 2.54;

# Output user name and height
print "$inputName, is $heightCM cm tall.";

Before Next Lecture

Next Lecture