in reply to Scope Between global and my

It sounds as if you want to do something like this:

# First, open a lexical block to hold the configuration variables. { # Now, open a configuration file to pull in data. my %settings; open my $config, "<configfile.dat" or die "Can't get started.\n$!"; while ( my $entry = <$config> ) { my ( $key, $value ) = split /\s+=\s+/, $entry; chomp $value; $settings{$key} = $value; } close $config; # Now, define the sub that will be the "getter" of # the lexical variables. sub mysub { print "Configuration file settings:\n"; foreach my $key ( %settings ) { print "$key = $settings{$key}\n"; } } # Next, close the lexical block. Only things within this block # will have access to the varibles declared with 'my' within it. } # This is the main program block: mysub();

The sub "mysub()" will have access to the lexical variables within the outter block, but since the block terminates before you get to the main part of the program, nobody else will have access to them. This is the first step in building a closure, for example.


Dave

Replies are listed 'Best First'.
Re: Re: Scope Between global and my
by SkipHuffman (Monk) on Apr 01, 2004 at 18:00 UTC

    Ok, I can see how a lexical block can do this for contiguous code segments. But I see a possible future problem in keeping track of this. Not moving a sub out of the block, etc.

    what I would really like is to be able to say. Ok, when I start sub-b from sub-a, I want to run sub-b in the same data space as sub-a.

      Then you probably want to use packages to segregate namespace.

      Honestly, if maintainability is an issue, and you are afraid that a lexical block enclosing a couple of subs is going to turn out to be a nightmare to keep track of, you're reached that point where packages and modules are there help you keep it all straight.


      Dave

        You may be right. This is actually already in a module, so I may need to split it into a sub module. Believe it or not, I am trying not to be too fancy because I am a perl novice.

        local seems to be doing the trick, but I have to turn off strict to use it and that makes me uncomfortable. Thanks