Docsity

Perl Programming: Control Flow, Foreach, Files, I/O, Subroutines, and Regex at UNC - Prof., Study notes of Programming Languages

Partial preview of the text

Download Perl Programming: Control Flow, Foreach, Files, I/O, Subroutines, and Regex at UNC - Prof. and more Study notes Programming Languages in PDF only on Docsity!

Lecture 6: Perl

COMP 524 Programming Language Concepts Aaron Block February 1, 2007

Based on notes by N. Fisher, F. Hernandez-Campos, and D. Stotts

Goal of Lecture

• Go into more detail on Perl

2

Control Flow

4

while($d<37){ $d++; }^ $sum^ +=^ $d;

until($d>=37){ $d++; }^ $sum +=^ $d;

Control Flow

5

do{ $d++; } $sumwhile^ += ($d<37);^ $d;

do{ $d++; } until ($d>=37);^ $sum +=^ $d;

Files and I/O

7

open(INDATA, “index.html”); #reading open(INDATA, “>index.html”); #writing open(INDATA, “>>index.html”); #appending

open(INDATA, close(INDATA); “index.html”) || die “Error”;

Files and I/O

8

open(INDATA, $in = ; “index.html”); #Gets one line as a scalar @all_in #all_in[0] = ; #Gets all lines as an array = first line

close(INDATA)^ #all_in[1]^ =^ second line

Files and I/O

10

open(OUTDATA, print OUTDATA ">index.html")“Out”; close(OUTDATA);

Files and I/O

11

print STDOUT “Out”;

Subroutines

13

print $retValue &aFunct(12,5); = &aFunc(12,5); aFunc(12,5); $x = noArgs(); $x = &noArgs;

Regular Expressions

14

/.at/ /[aeiou]/ #matches #matches single character “cat”, “bat”, but not “at” /[0-9]/ /[0-9]/ #match one char #match zero or more chars from range /[^0-9]/ /cmp/ #“cccmp”, #match zero or more chars NOT in range “cmp”, “mp”, NOT “cp” /a+t/ /a?t/ #“aaat”,#zero or “at”, “t”one “a”s, “at” or “t” not “aaaat” /^on/ /on$/ #start... “on the” NOT “the#end... “the on” not “on the” on” /cat/i /**/ #ignore#match “**”case

Regular Expressions

• Replace “foo” with “bar” by “s/foo/bar/”

• Only works for first match.

• To apply to all use “s/foo/bar/g”

16

$a = $a =~ “Hello s/World/Mars/; World World”; print ($a. “\n”); #Print “Hello Mars World”

$a = $a =~ “Hello s/World/Mars/g; World World”; print ($a. “\n”); #Print “Hello Mars Mars”

Regular Expressions

• Replace regardless of case use “s/foo/bar/i”

• Combine with “global”

17

$a = $a =~ “Hello s/world/Mars/i; World World”; print ($a. “\n”); #Print “Hello Mars World”

$a = $a =~ “Hello s/world/Mars/gi; World World”; print ($a. “\n”); #Print “Hello Mars Mars”

System Interactions

19

• Run a system command foo use system(“foo”);

• To get return from system use “backticks” ( ` )

system(“ls”); #runs “ls”

$retVal print “$retVal\n”; #Prints working Dir. = pwd;

Pipes

• Open a pipe as a filehandle

• Pipe from a process

20

$pid while(){ print; } = open(DATAGEN, “ls -lrt |”) || die “oops\n”; close(DATAGEN) || die “oops again\n”;

$pid $a = =ls; open(SINK, “| more”) || die “oops\n”; print close(SINK) SINK $a; || #Pipes output fromdie “oops again\n”; “ls” into “more”