Loading ...
Sorry, an error occurred while loading the content.
 

Re: [PBML] Small Scoping question.

Expand Messages
  • Charles K. Clarkson
    Franki ... Think hashes and references. my $global = get_var_from_file ($file_name); sub get_var_from_file { # do some fancy stuff
    Message 1 of 5 , Jan 2, 2002
      "Franki" <frankieh@...>

      : Just thougth of a related question..
      :
      : What do you do, if you have a sub that opens a file and assigns
      : a value from that file to a variable..(purely hyperthetical, I could
      : think of a dozen examples of what I mean that would have the
      : same problem...)
      :
      : and that variable needs to be available to other subs and stuff
      : throughout the script.
      :
      : if you used "my" in that scenario, would not the variable go
      : "out of scope" once that sub had run and its value not be
      : available to anything outside it?
      :
      : If I am right, how could you make it available outside the sub?
      : Do you have to use "return" to make it available? is that how
      : it works?
      :
      : IF that is correct, does that mean that the 100% correct and
      : proper way to do it would be to pass all needed variables to
      : the sub as parameters, and return the ones you want available
      : to other areas of the script?
      :
      : (I am just trying to improve my habbits now, before getting
      : to used to doing it the way I have been.)

      Think hashes and references.

      my $global = get_var_from_file ($file_name);

      sub get_var_from_file {
      # do some fancy stuff getting a hundred variables from
      # $file_name and place them in a hash %globals
      return \%global;
      }

      You can dereference the hash with:

      $$global{base}

      This way you are only returning a single scalar (the reference)
      from the sub. If you undef the reference or it goes out of scope
      the hash goes away too. Assuming nothing else is pointing to it.
      Calling it global helps most anyone realize where it came from.

      If you need to pass a lot of variables into a sub, consider
      using a reference:

      my $cool_members = cool(\@members);

      my $cool_members = cool( [@alumni, @pledges, @members ] );



      HTH,
      Charles K. Clarkson
      Clarkson Energy Homes, Inc.
      254 968-8328



      Is there another word for synonym?
    Your message has been successfully submitted and would be delivered to recipients shortly.