Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Stupid question

by chipmunk (Parson)
on Dec 07, 2000 at 02:37 UTC ( [id://45361]=note: print w/replies, xml ) Need Help??


in reply to Stupid question

By main section, you mean 'code not in subroutines', right? As you've discovered, Perl considers subroutines to be part of the block in which they were defined, so they have access to all the lexical variables of that block.

If you want to limit the scope of a lexical variable, you need to declare it inside a block, like this:

#!/usr/bin/perl -w use strict; sub foo(); # main: { my $bar = "I can see you"; &foo; } sub foo() { print "inside foo: $bar\n"; return(0); }
With use strict, that code doesn't compile, because the $bar in foo() hasn't been declared, which is the effect you want.

Replies are listed 'Best First'.
Re: Re: Stupid question
by code24 (Initiate) on Dec 07, 2000 at 02:42 UTC
    Thanks, that helps.

    Is that considered a 'good' format, or should I just not worry about the subroutines access to these variables?
      I personally think that 'main' variables, while able to be accessed by subroutines declared in the same package, are safe enough, as long as you don't access them directly in a subroutine.
      use strict; my $foo = 'yo'; &bar($foo); print "$foo\n"; sub bar { my $bar = shift; $bar .= ' dude'; }
      Declare you variables in main, just don't use them directly in your subroutines and you'll be okay.

      Jeff

      L-LL-L--L-LL-L--L-LL-L--
      -R--R-RR-R--R-RR-R--R-RR
      F--F--F--F--F--F--F--F--
      (the triplet paradiddle)
      
      If you are worried about the subroutines accessing these variables, this is the way to avoid the problem; go for it! It is a good programming practice to have subroutines get all their input through the argument list and not through external variables, because it makes the code more maintainable.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-04-23 16:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found