>>>>> "MM" == Mike McClain <[email protected]> writes:

  MM> Here's a simple example that illustrates the problem I've run into:
  MM> perl -le'
  MM> show();
  MM> {   my @fibs = (0,1,1); my ($x, $y) = (1,2);
  MM>     sub show
  MM>     {   print "x=$x\ty=$y\t\$#fibs=$#fibs\tfibs=@fibs\tscalar \@fibs = ",
  MM>             scalar @fibs;
  MM>     };
  MM>     $fibs[$#fibs+1] = 2;
  MM> }
  MM> show();
  MM> '
  MM> x=      y=      $#fibs=-1       fibs=   scalar @fibs = 0
  MM> x=1     y=2     $#fibs=3        fibs=0 1 1 2    scalar @fibs = 4

  MM> The first time show() runs it acts as if it can't see $x, $y or @fibs.
  MM> The second time it does yet the interpreter had to have seen $x, $y
  MM> and @fibs in order to find the definition of show().

  MM>     I've grown accustomed to writing 'C' style code in Perl with
  MM> main before the subs rather than shell or Forth style but here it
  MM> seems to fail.

this is perl, not c. don't write c style or expect c style to make sense.

  MM>     I know I can use memoize but where I ran across this problem
  MM> was in trying to write a fibonacci routine that would take
  MM> advantage of any previously calculated values rather than starting
  MM> at 1 again as a memoized function would be required to do.

this is a simple problem and it is in your understanding of how perl
works, in particular how code is compiled vs run.

perl first compiles code to an intermediate form. then it executes
it. my commands have two phases, the declare phase which is handled
during the compiling and the assignment phase which is handled at run
time. the first time you call show(), the vars are declared but NOT
initialized. the second time you call show they are initialized.

you can solve this in several ways. one, use a BEGIN block instead of
the plain block you have. why do you have a block there at all? do you
need private scoping? the BEGIN block executes its code at compile time
so the initialization will happen before the first call to show.

you can also put the initializing code (not the declarations) in its own
sub and call that first before show is called. that way you control the
time things happen.

finally, why do you want to call show before the block anyhow? it won't
work as is and it can be subtly broken in other ways.

uri

-- 
Uri Guttman  ------  [email protected]  --------  http://www.sysarch.com --
-----  Perl Code Review , Architecture, Development, Training, Support ------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------

-- 
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/


Reply via email to