Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Question of scope

by stephen (Priest)
on May 07, 2002 at 03:43 UTC ( #164515=note: print w/ replies, xml ) Need Help??


in reply to Question of scope

Be careful, for here you are using a closure. Remember, when an anonymous subroutine is defined, it uses whatever lexical variables are in scope at the time it was created. So:

use strict; my @foo = (); my $pushit = sub { push @foo, @_; }; $pushit->('apple'); $pushit->('orange'); print @foo, "\n";
will print "appleorange", but
use strict; my @foo = (); my $pushit = sub { push @foo, @_; }; my @foo = (); $pushit->('apple'); $pushit->('orange'); print @foo, "\n";
will print nothing, since the @foo that is printed is not the same @foo that is being populated. (That'll also happen if you're not using strict, and somehow only declare @foo after the closure is created.) If this is the case, it'll show up if you turn warnings on... if the new @foo (or @coords in your case) is in the same scope as the other one. If @coords is file-scoped, you might well want to use 'our' instead of 'my'... that way you're guaranteed a single variable.

stephen


Comment on Re: Question of scope
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://164515]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2014-12-22 12:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (116 votes), past polls