Workshop

 <  Day Day Up  >  

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

A3:

b. Variables declared with local are called dynamically scoped variables.

Activities

  • Use the functions from the statistics exercise in this hour and the word-counting code from Hour 7, "Hashes," to examine the length of the words in a document. Compute their mean, median, and standard deviation.

  • Write a function to print part of the Fibonacci series. This series begins 0, 1, 1, 2, 3, 5, 8 and continues forever. The Fibonacci series is a recurring pattern in mathematics and nature. Each successive number is the sum of the previous two (except 0 and 1). These numbers can be computed iteratively or recursively.

 <  Day Day Up  >  


SAMS Teach Yourself Perl in 24 Hours
Sams Teach Yourself Perl in 24 Hours (3rd Edition)
ISBN: 0672327937
EAN: 2147483647
Year: 2005
Pages: 241

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net