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)
Q1:After you run bar($a, $b), what is the value in $b?
  1. 5

  2. 100

  3. 68

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

  2. 68

  3. undef

Q3:Inside foo(), what is $b?
  1. Lexically scoped

  2. Dynamically scoped

  3. Globally scoped

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, ...

Get Sams Teach Yourself Perl in 24 Hours 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.