Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Question of scope

by stephen (Priest)
on May 07, 2002 at 03:43 UTC ( [id://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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-03-29 07:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found