23
Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Embed Size (px)

Citation preview

Page 1: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Introduction to Perl

October 4, 2004

Class Meeting 7

* Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Page 2: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 2

Perl Background

Practical Extraction and Report Language (Perl)

Created by Larry Wall, mid-1980'sLanguage combining capabilities of shell

programming, awk, grep, lex, sed, and a number of other UNIX utilities

Powerful, complex scripting languageWe learn just a bit!

Page 3: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 3

Scalars

Basic data type in Perl is scalarMost scalar values are numbers or

character stringsProgrammer forces interpretation of a

scalar value as a number or string by operations used

Special scalar value undef is neither number nor string, just "undefined"

Page 4: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 4

Numbers

Integers: 45, 974, -892, 0Real numbers: 45.0, 10.237, -101.1, 2.5e-3

Octal: 055Hexadecimal: 0x2dBinary: 0b101101

Page 5: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 5

Numeric Operators

Arithmetic: 4+5, 9-7, -9*-3, 10/3Modulus (remainder): 102 % 9 is 3

Comparisons: <, >, <=, >=, ==, !=Spaceship: <=> (-1, 0, or 1)

LogicalAnd && andOr || orNot ! not

Page 6: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 6

Strings

Zero or more characters: "", "one"No concept of null-terminationSingle (literal) quotes

'tab\tnl\n' tab\tnl\n 9Double (interpreted) quotes

"tab\tnl\n" tab_nl_ 7Escaped double quote

"Here's a double quote \"."

Page 7: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 7

String Operators

Concatenation: "Learning "."Perl"Comparisons: lt, gt, le, ge, eq, neIndex: position of a substring in a string

index('Learning Perl','rni') 3index("Learning Perl",'nr') -1

Substring: select a substringsubstr('Learning Perl',1,2) ea

String positions start at 0

Page 8: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 8

Scalar Variables

Scalar variable identifier begins with $$colors = "red green blue";$count = $count+1;

Shortcuts and alternatives:$colors .= ' purple';$count += 1;$count++;

Interpolation: "Count is $count.\n"

Page 9: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 9

Lists

Sequence of scalars(5.7,"house\tbarn",'-9.2')

qw shortcut — equivalent lists:("VT","UNC","NCSU","UVa","Wake")qw/ VT UNC NCSU UVa Wake /qw{ VT UNC

NCSU UVaWake

}

Page 10: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 10

Arrays

An array is a list-valued variableArray identifier begins with @

@colors = qw(red green blue);Array element reference: $id[index]

$colors[2] # Value is 'blue'$colors[8] = 'purple';substr($colors[1],0,3) # 'gre'

Page 11: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 11

Simple Perl Script

#!/usr/bin/perl$dotted = join('.',@ARGV);@ping = `ping -c 1 $dotted`;print @ping[0..1];

Result:[cs2204@peach cs2204]$ dot_ping www cslab vt eduPING owlstation.cs.vt.edu (128.173.40.52) 56(84)

bytes of data.64 bytes from 128.173.40.52: icmp_seq=1 ttl=64

time=0.536 ms

Page 12: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 12

Numeric Functions

ASCII code — ord('?') is 63 ASCII character — chr(63) is '?' Absolute value — abs(-11) is 11 Integer value — int(295.143) is 295 Square root — sqrt(16) is 4 Natural logarithm — log(295.143) is 5.69 Integer value — int(295.143) is 295 Random number — rand(10) was 4.94028

Page 13: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 13

String Functions

Length — length('Learning Perl') is 13 Find substring — index rindex Extract substring — substr Lower case — lc('9Jp.iR') is '9jp.ir' Upper case — uc('9Jp.iR') is '9JP.IR' Remove last character — chop($word); Remove newline at end — chomp($line);

Page 14: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 14

Array Functions

Stack; top on the right — @stack=qw/1 2 3/; push(@stack,'top') updates @stack to 1 2 3 'top' pop(@stack) updates @stack to 1 2 3 returns 'top'

Stack; top on the left — @stack=qw/4 7 a/; unshift(@stack,8) updates @stack to 8 4 7 'a' shift(@stack) updates @stack to 8 4 7 returns 'a'

Reverse a list Reverse qw/8 l a p 7/ returns qw/7 p a l 8/

Page 15: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 15

Array Functions (Continued)

Array to string @words = qw/9b4 x.; pbj/; $words=join('--',@words); is '9b4--x.;--pbj'

String to array split(/b/,$words) is qw/9 4--x.;--p j/

Sorting — lexicographic order sort qw/red green blue/ returns qw/blue green red/

Sorting — numerical order sort { $a <=> $b } (94,-1,55) returns (-1,55,94)

Page 16: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 16

Input

Text files Sequence of lines, each terminated by a newline

File access by a file handle — standard input STDIN

Read a line $line = <STDIN>;

Read remaining lines @lines = <STDIN>;

Page 17: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 17

Output

Standard output — STDOUT print 'A line to', " standard output\n";

Standard error — STDERR print STDERR "Arguments OK\n"; warn "Unable to find config file.\n"; die "Unexpected system error";

Page 18: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 18

if Statementt

if (condition) {

statements;

} elsif (condition) {

statements;

} else {

statements;

}

if (not defined $ARGV[0]) {

die "Usage:\n\tpaint [COLOR]\n";

}

Page 19: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 19

while Statementt

while (condition) {

statements;

}

$term = shift(@ARGV); $ln = 0;

while ($line = <STDIN>) {

chomp $line; $ln++;

if ($line eq $term) {

print "Term $term on line $ln.\n";

break;

}

}

Page 20: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 20

for Statement

for (initialization; test; increment) {

statements;

}

for ($i = 0; $i < length($line); $i++) {

if (lc($char) eq substr($line,$i,1)) {

print "Character $char found.\n"; last;

} elsif (uc($char) eq substr($line,$i,1)) {

print "Character $char found.\n"; last;

}

}

Page 21: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 21

foreach Statement

foreach $x (@y) { # execute for each element of list

statements;

}

foreach $color (qw/red green blue purple/) {

print "$color is a color!\n";

}

Page 22: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 22

Sample Script

#!/usr/bin/perl

$word = shift(@ARGV);

while ($line = <STDIN>) {

if (index($line,$word) > -1) {

unshift(@CONTAINS,$line);

} else {

unshift(@LACKS,$line);

}

}

foreach $line (@CONTAINS) {

print $line;

}

Page 23: Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004

Lenwood Heath, Virginia Tech, Fall, 2004 23

Topics for Next Lecture

SubroutinesRegular expressionsHashesFile input/outputFile testsInvoking UNIX commands