CS 216 Quiz 8 Fall 2012 ANSWERS

bewgrosseteteΛογισμικό & κατασκευή λογ/κού

13 Δεκ 2013 (πριν από 3 χρόνια και 8 μήνες)

68 εμφανίσεις

CS 216 Quiz 8 Fall 2012 ANSWERS

Name________________________________________________ Section________

70 points. Closed book. No electronic device can be used.

1.(40)What is printed by this Perl program (mark the lines printed):

Contents of perlQ1.txt: IF

PRINTED MARK HERE (Y/N) ON EACH LINE:

UL Lex 2 data1

Pattern 1: ___ Pattern 2:____ Pattern 3:______

UL Lex 3 data2 Pattern 1: ___ Pattern 2:____Y Pattern 3:______Y

UK Lou 2 data3 Pattern 1: ___Y Pattern 2:____ Pattern 3:______

UK Lou 3 data4 Pattern 1: _
__ Pattern 2:____ Pattern 3:______Y

UL Lex 1 data5 Pattern 1: ___ Pattern 2:____ Pattern 3:______

UK Lou 4 data6 Pattern 1: ___ Pattern 2:____ Pattern 3:______

UL

Rich 2 data7 Pattern 1: ___ Pattern 2:____ Pattern 3:______

#!/usr/local/bin/perl

$infile =

"perlQ1.txt";

open(SINPUTF, "<$infile");

$index = 0;

while (defined($sinput = <SINPUTF>)) {

$indata[$index] = $sinput;

$index++;

}

for ($count = 0;$count<$index;$count++) {

$data = shift(@indata);

if ($data =~ /^(UK)
\
s+(Lou)
\
s+[12]
\
s+/) {

print

"pattern 1: $data
\
n";

}

if ($data =~ /^(UL)
\
s+(
\
w+)
\
s+[^12]
\
s+/) {

print "pattern 2: $data
\
n";

}

if ($data =~ /^(
\
w+)
\
s+(Lou|Lex)
\
s+[3]
\
s+/) {

print "pattern 3: $data
\
n";

}

}

close(SINPUTF);














QUESTION 2 ON OTHER SIDE

2. (30) List the matches for each line of input:

example ABCDEF match 1 match 2

ABCABC56 no match (make sure you put this, don’t leave blank)

(samples only, they do not match patterns below)

Lines entered as input to the program from the keyboard:

Input

to the program

qwertabc123abc123abcxyz match 1

abc123zzz45abcxyz

abcpqr%^5f4ty^&xyaxyzabc match 2

abc55b5abcdef66xyz match 2

#!/usr/local/bin/perl

while (defined($word = <STDIN>)) {

chop $word; # remove trailing
\
n

if ($word =~ /(abc)(123)
\
w*
\
2
\
1/) {

pr
int "match 1 $word
\
n";

}

if ($word =~ /^(abc)+.+
\
d[a
-
z]
\
d[a
-
z]+.+(xyz)/) {

print "match 2 $word
\
n";

}

}



Summary of Perl Pattern Matching using Regular Expressions

* zero or more characters

+ 1 or more characters

? zero or 1 characters

^ start of line

$
end of line

[] group of characters

{} repetition of a pattern matching group

^ (within grouping) none of these characters

| or

. any one character

() subgroup

$1 first extraction text ($2 second extraction, etc.)

\
1 first subgroup text in a pattern match

(
\

second subgroup, etc.)

g global search (don’t start at beginning of text)

i ignore case

\

escape (treat next character as a normal character)

\
w

alphabetic, numeric, or _ ("word
-
like")

\
W

not alphabetic, numeric, or _ ("not word
-
like")

\
d

numeric ("digit")

\
D

not numeric ("not digit")

\
s

space, tab, newline, carriage return ("space")

\
S

not space, tab, newline, carriage return ("not space")