From: "John W. Krahn" <jwkr...@shaw.ca>
> Bryan Harris wrote:
> > 
> > [stuff cut out]
> > 
> >> It is usually best to declare variables in the smallest scope possible 
> >> so:
> >>
> >> while (more work to do)
> >> {
> >>   my @array = split $string;
> >>
> >>   # do work on array
> >> }
> >>
> > 
> > Doesn't that try to re-localize (?) the @array variable every time 
> > through the loop?  i.e. doesn't it re-run the my() function every time 
> > through the loop?  For some reason I thought that was a no-no.
> 
> my() happens when the code is compiled so it is *not* re-run every time 
> through the loop.  The assignment happens when the code is run so it is 
> re-run every time.

That's not entirely true. There is compiletime and runtime behaviour 
of my(). It doesn't just silence 'use strict', it also allocates a 
new variable. Each time you enter the loop body. See this:

for (1..10) {
  my $x = 1;
  print "The \$x is at " . \$x . "\n";
}
print "versus\n";
my @arr;
for (1..10) {
  my $x = 1;
  print "The \$x is at " . \$x . "\n";
  push @arr, \$x;
}

As you can see in the first case it allocates the same memory, in the 
second, because I remember the address, it has to allocate a new 
chunk of memory every time.


OTOH, you should not care about this, the allocation is pretty quick, 
especially if it can reallocate the same bit of memory every time.

Jenda
===== je...@krynicky.cz === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed 
to get drunk and croon as much as they like.
        -- Terry Pratchett in Sourcery


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to