Introduction to Perl

This lecture notes is based on Prof Doreen De Leon's lectures.

Reading

Learning Perl, Chapter 2.

What is Perl?

Start Doing Perl

On PC

Download

Run a Perl program.

On Unix

Scalar Data

Example
print 1.25, "\n", 255.1, "\n", 7.25e3;
Output
1.25
255.1
7250


print 'abc\n'; #abc\n
print "\nabc\n";# newline abc newline 
print 'I\'m Charles.'; #I'm Charles 
Output
abc\n
abc
I'm Charles.

Scalar Operators

For Numbers

Example
print 1.1**2; #1.21
print "\n"; # new line  
print 7.5%3; #1

1.21
1

For Strings

print "hello"."world"; #helloworld
print "\n"; # new line  
print "hello".' '."world"; # hello world
print "\n"; # new line  
print "hello" x 3; #hellohellohello
print "\n"; # new line  
print 2.3; # 2.3
print "\n"; # new line  
print 2 . 3; # 23
print "\n"; # new line  
print 2 x 3; # 222 

helloworld
hello world
hellohellohello
2.3
23
222

if("abc" lt "def") {
  print "abc < def\n";
}

Conversion Between Numbers and Strings

print "2" + "3"; # 2 + 3
print "\n";
print "2".3; # 23
print "\n";
print 2 x 3; # 222
print "\n";
print "12abc"*"5abc"; # 12*5

5
23
222
60

Scalar Variables

Scalar Operators and Functions

$x = 123;
$x+=2;
print $x;
print "\n";
$x = "abc";
$y = "def";
$z = $x.$y;
print $z;
print "\n";
print $x x 3;
print "\n";
print 125, " is a number but ", $x, " is not a number.\n";

125
abcdef
abcabcabc
125 is a number but abc is not a number.

The chop and chomp Functions

$x = "abcde";
print $x, "\n";
chop($x);
print $x, "\n"; #abcd
$x = "abcde\n";
#print $x, "\n";
chomp($x); # the \n is removied
print $x, "\n";
print "how many empty lines?";

abcde
abcd
abcde
how many empty lines?

Variables in Strings

$name = "Charles";
$age = 21;
print "$name is $age.\n"; #Charles is 21.
$name = "Amy";
$age = 18;
print "$name is $age.\n"; #Amy is 18.
print "Dollar sign \$\n"; #Dollar sign $

$what = "apple";
print "He ate two $whats.\n"; #Not correct, $whats is not known
print "He ate two ${what}s.\n"; # He ate 2 apples.
print "He ate two $what"."s.\n"; # same as above
print 'He ate two $what.\n'; #He ate two $what

Charles is 21.
Amy is 18.
Dollar sign $
Use of uninitialized valu
He ate two .
He ate two apples.
He ate two apples.
He ate two $what.\n

Standard Input and Output

$line = <STDIN>;
if($line eq "\n") {
    print "That was just a blank line!\n";
} else {
    print "That line of input was: $line";
}