Exercise 1: Write a Perl program that reads a string and a number. Lets say the string is 'hello' and the number is 3. The program should print:
Here is the string 'hello' printed 3 times: hello hello hello
Answer:
print "String: "; chop($string = <STDIN>); print "Number: "; chop($number = <STDIN>); print "Here is the string $string printed $number times:\n"; $string .= "\n"; print $string x $number;
Exercise 2: Explain where in your program from exercise 1 type coercion is happening.
Answer: In the last line where the string $number is used at a number.
Exercise 3: Give an example of a Perl program where the fact that expressions can have side-effects causes unpredictable behavior. Try to come up with a different one than from lecture.
$b = --a * ++a;
Exercise 4: Why aren't Perl style associative arrays available in C?
Answer: It would require C to provide memory management and this conflicts with the design goals of C.
Exercise 5: Write a EBNF grammar for the if-else construct in Perl. You can use <expr> for expressions and <stmt> for statements.
<if-else> ::= if <expr> then <block> [else <block>] <block> ::= '{' <stmt> {, <stmt> } '}'
Exercise 6: Write a Perl program to parse this mail file and create a file with all the headers on the first line and all the data values on the second line. Each field should be in quotes and the fields should be separated by commas. The resulting file should look something like this file. The first header should be "HW" and the first data value should be "1". Otherwise, it doesn't matter what order the headers appear in as long as they correspond correctly to the data values.
$quote = '"'; $comma = ','; @in = grep (!/---/, <STDIN>); # eliminate line separators @in = grep (/\S/, @in); # eliminate blank lines ($h1,$h2,$h3, @in) = @in; # pull off header foreach $i (0 .. $#in) { chomp($in[$i]); # delete newline $in[$i] =~ s/"//g; # get rid of quotes $in[$i] =~ s/::/-/g; # get rid of pesky :: ($key, $val) = split(/: /,$in[$i],2); # process multiple line values if (defined($val)) { @keyList = (@keyList, $comma, $quote, $key, $quote); @values = (@values, $quote, $comma, $quote, $val ); } else { @values = (@values, ' ', $in[$i]); } } print ($quote,HW,$quote,@keyList,"\n",$quote,1, @values);