Workshop

Quiz

Examine the following block of code:

sub bar {
    ($a,$b)=@_;
    $b=100;
    $a=$a+1;
}
sub foo {
    my($a)=67;
    local($b)=@_;
    bar($a, $b);
}
foo(5,10)
1:After you run bar($a, $b), what is the value in $b?
  1. 5

  2. 100

  3. 68

2:What is the return value from foo()?
  1. 67

  2. 68

  3. undef

3:Inside foo(), how is $b scoped?
  1. Lexically

  2. Dynamically

  3. Globally

Answers

A1: b. $b is declared with local in foo() so that every called subroutine shares the same value for $b (unless they later declare $b again with local or my). After calling bar(), where $b is modified, $b is set to 100.
A2: b. Surprised? The last statement in foo() is bar($a, $b). bar() returns 68 because the value of $a is passed to bar(), and it's incremented. foo() returns the value of the last expression, which is ...

Get SAMS Teach Yourself Perl in 24 Hours THIRD EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.