Workshop

The workshop provides quiz questions to help you solidify your understanding of the material covered and exercises to give you experience in using what you've learned. Try and understand the quiz and exercise answers before you go on to tomorrow's lesson.

Quiz

1:What is a slice? How does a slice affect the original list?
A1: A slice is some subset of the elements in an array or hash. Slices do not affect the original list; they copy the sliced elements into the new list. Compare with elements extracted using splice, where the original array or list is permanently changed.
2:What are the $a and $b variables used for in sort routines?
A2: The $a and $b variables in a sort routine are local to that routine and refer to two list elements being compared. Use $a and $b to write your sort routines to do what you want.
3:What do the <=> and cmp operators do? What is the difference between them?
A3: The <=> and cmp operators take two operands and return -1 if the first is less than the second, 0 if the two are equal, and 1 if the first is larger than the second. Although this behavior might not seem overly useful in ordinary use, these operators work exceptionally well for sort routines, which need exactly that kind of output to sort the elements in a list.

The difference between <=> and cmp is the same as the difference between == and eq; the former is used for numbers, the latter for strings.

4:The grep function takes an expression or a block as its first argument. What is this block used for?
A4: The expression or block as an argument to grep is used as a test to determine whether a particular list element (as stored in $_) will be saved in the final list grep returns. If the expression or block returns true, the list element is saved.
5:How can you use splice to add elements to an array? Replace two elements with a list of four elements?
A5: Add elements to an array with splice by using a length argument (the third argument) of 0. This will remove no elements, and add the new elements at the position specified by the offset:
splice(@array, 0, 0, (1,2,3,4); # add (1,2,3,4) at the start of the array

To replace two items with four items, use 2 as the length argument, and the items to add as a list:

splice(@array, 0, 2, (1,2,3,4); # remove first two elements and replace with (1,2,3,4)

6:How can you return a value from the block in map?
A6: To return a value from the block of expressions in map, make sure the last thing to be evaluated in the block is the thing you want to return (and therefore to be passed onto the new list).

Exercises

1:Rewrite the following expressions using splice:
push @list, 1;
push @list, (2,3,4);
$list[5] = "foo";
shift @list;

A1: Here are the answers:
splice(@list, $#list+1, 0, 1);
splice(@list, $#list+1, 0, (2,3,4));
splice(@list, 5, 1, "foo");
splice(@list, 0, 1);

2:BUG BUSTERS: What's wrong with this code (HINT: there might be multiple errors)?
while ($i <= $#list) {
   $str = @novel[$i++];
   push @final, reverse $str;
}

A2: There are multiple bugs and conceptual errors in this snippet of code. The first is in the second line; the array access expression here is actually an array splice, so you'll end up with an array of one element instead of an actual string. Perl warnings will catch this one.

But even if you fix that error, the string will not be reversed, because in the third line reverse is being called in a list context, so the string is interpreted as a list of one element. Use the scalar function to create a scalar context for reverse.

3:BUG BUSTERS: How about this code?
while ($pos < (length $str) and $pos != -1) {
    $pos = index($str, $key, $pos);
    if ($pos != -1 ) {
        $count++;
    }
}

A3: At some point inside the loop, you have to increment the current position. Otherwise, the loop will continue to find the same substring at the same position, over and over again, and turn into an infinite loop.
4:Write a version of this expression using a foreach loop and push:
@list2 = grep {$_ < 5 }  @list;

A4: Here's one answer:
foreach (@list) {
   if ($_ < 5) {
       push @list2, $_;
   }
}

5:Write a script that prompts you for a string and a character, and then returns the number of times that character occurs in the string. Use the index function.
A5: Here's one answer:
#!/usr/bin/perl -w

$str = '';
$key = '';
$pos = 0;
$count = 0;

print "Enter the string to search: ";
chomp($str = <STDIN>);
print "Enter the character to count: ";
chomp($key = <STDIN>);

while ($pos < (length $str) and $pos != -1) {
    $pos = index($str, $key, $pos);

    if ($pos != -1 ) {
        $count++;
        $pos++;
    }
}

print "$key appears in the string $count times.
";

6:Rewrite the script in #5 without using index (or patterns, if you already know something of patterns). Hint: try using grep.
A6: Here's one answer:
#!/usr/bin/perl -w

$str = '';
$key = '';
$pos = 0;
$count = 0;

print "Enter the string to search: ";
chomp($str = <STDIN>);
print "Enter the character to count: ";
chomp($key = <STDIN>);

@chars = split('',$str);
$count = grep {$_ eq $key}  @chars;

print "$key appears in the string $count times.
";

The sneaky part about this example is the line that uses split to convert the string into a list of characters. After you have a list using grep is easy.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset