CIW Course Revision Site

Tutor Marked Assignment PL TMA-06

In a Nutshell - CIW Course Section 2 Part B

PL TMA-06 - CD Access Code: 15813

Q1. What is the main advantage of subroutines?

Q2. How would you invoke the anonymous subroutine called AnoSub?

Q3. Which of these scripts demonstrates the correct use of a subroutine?

a) $a = 2; $b = 5;
sub multiply {
    $a * $b;
}
print (multiply());
b) $a = 2; $b = 5;
sub multiply {
    ($x, $y) = @_;
    $x * $y;
}
print (multiply($a, $b));
c) $a = 2; $b = 5;
sub multiply {
    ($x, $y) = $_;
    return $x * $y;
}
print (multiply($a, $b));
d) $a = 2; $b = 5;
sub multiply {
    ($x, $y) = @_;
    return $x * $y;
}
print (multiply($a, $b));

 

Q4. What would be displayed by the following Perl statements?

sub multiply {
    $total = 1;
    foreach ($_) {
        $total *= $_;
    }
}
print (multiply (1, 2, 3, 4, 5, 6));

Hint: Take a look at the code closely, and then 'return' and look again!

Q5. What will be displayed as a value of i after this script?

sub sort_by_num {
    $i++;
    return $a <=> $b;
}
$i = 0; @arr = (500,1,400,5);
foreach (sort sort_by_num(@arr)) {
    print ("$_\n");
}
print "i = $i";

This one should really be typed up and run. I got it correct, but I don't really understand what it's doing, even after an explanation. $i is incremented each time sort_by_num is called, but this, apparently, depends on the original array order, i.e. how ordered it was to begin with.

Q6. The my operator takes a scalar, array or hash name and creates unique, local versions of the variable within the subroutine.

Q7. What does "Dereferencing" mean?

Q8. Perl supports two types of references, ________ and ________.

Q9. What are the missing commands in positions 'a' and 'b' if the required display output is "Value '4D' pos.# 4."?

%has = (A => "1A", B => "2B", C => "3C");
&Aref = \%has;
pandp("D", $Aref);
sub pandp {
    local ($newItem, $Nref) = @_;
    my $c = counthash("Nref") + 1;
    ______a______ = $c.$newItem;
    print("Value '______a______' pos.\# $c.\n");
}
sub counthash {
    my ($tocount) = @_;
    my $x = 0;
    foreach $key (keys(______b______)) { $x++; }
    return $x;
}

I have absolutely no idea about this question! I have been given the correct answer and an explanation, and I still don't understand any of it.

Q10. What would be displayed by the following Perl statements?

@arr1 = (1, 2); @arr2 = 3, 4);
man_arr(\@arr1, \@arr2);
sub man_arr {
    my ($list1, $list2) - @_;
    my $i = 0;
    foreach (@list1) {
        @$list1[$i] = @arr1[$i] + @arr2[$i];
        @$list2[$i] = @arr2[$i] - 1;
        print ($$list1[$i]." - ".@arr1[$i]);
        print ("\n");
        print ($$list2[$i]." - ".@arr2[$i]);
        print ("\n");
        $i++;
    }
}

Design by Stephen

Certified Internet Webmaster

Page last Edited: 25 Nov 2011