introduction to perl - virginia techcourses.cs.vt.edu/~cs2204/fall2007/notes/perl-1.pdf ·...

12
1 Introduction to Perl Sept 24, 2007 Class Meeting 6 * 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's Language combining capabilities of shell programming, awk, grep, lex, sed, and a number of other UNIX utilities Powerful, complex scripting language We learn just a bit!

Upload: others

Post on 19-Jul-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

1

Introduction to Perl

Sept 24, 2007

Class Meeting 6

* 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's

� Language combining capabilities of shell programming, awk, grep, lex, sed, and

a number of other UNIX utilities

� Powerful, complex scripting language

� We learn just a bit!

Page 2: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

2

Lenwood Heath, Virginia Tech, Fall, 2004 3

Scalars

� Basic data type in Perl is scalar

� Most scalar values are numbers or

character strings

� Programmer 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"

Lenwood Heath, Virginia Tech, Fall, 2004 4

Numbers

� Integers: 45, 974, -892, 0

� Real numbers: 45.0, 10.237, -101.1,

2.5e-3

� Octal: 055

� Hexadecimal: 0x2d

� Binary: 0b101101

Page 3: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

3

Lenwood Heath, Virginia Tech, Fall, 2004 5

Numeric Operators

� Arithmetic: 4+5, 9-7, -9*-3, 10/3

� Modulus (remainder): 102 % 9 is 3

� Comparisons: <, >, <=, >=, ==, !=

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

� Logical

� And && and

� Or || or

� Not ! not

Lenwood Heath, Virginia Tech, Fall, 2004 6

Strings

� Zero or more characters: "", "one"

� No concept of null-termination

� Single (literal) quotes

� 'tab\tnl\n' tab\tnl\n 9

� Double (interpreted) quotes

� "tab\tnl\n" tab_nl_ 7

� Escaped double quote

� "Here's a double quote \"."

Page 4: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

4

Lenwood Heath, Virginia Tech, Fall, 2004 7

String Operators

� Concatenation: "Learning "."Perl"

� Comparisons: lt, gt, le, ge, eq, ne

� Index: position of a substring in a string

� index('Learning Perl','rni') 3

� index("Learning Perl",'nr') -1

� Substring: select a substring

� substr('Learning Perl',1,2) ea

� String positions start at 0

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 5: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

5

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 UVa

Wake

}

Lenwood Heath, Virginia Tech, Fall, 2004 10

Arrays

� An array is a list-valued variable

� Array 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 6: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

6

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 edu

PING 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

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 7: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

7

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);

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 8: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

8

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)

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 9: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

9

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";

Lenwood Heath, Virginia Tech, Fall, 2004 18

if Statement

if (condition) {

statements;

} elsif (condition) {

statements;

} else {

statements;

}

if (not defined $ARGV[0]) {

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

}

Page 10: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

10

Lenwood Heath, Virginia Tech, Fall, 2004 19

while Statement

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;

}

}

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 11: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

11

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";

}

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 12: Introduction to Perl - Virginia Techcourses.cs.vt.edu/~cs2204/fall2007/notes/Perl-1.pdf · Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by LenwoodHeath, Virginia

12

Lenwood Heath, Virginia Tech, Fall, 2004 23

Topics for Next Lecture

� Subroutines

� Regular expressions

� Hashes

� File input/output

� File tests

� Invoking UNIX commands