Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a function that is called like so:
$html = function();
Within this function, I am checking the values in a hash that is a global variable (declared with 'our'). Values in this hash are assigned by a method call. I don't like this set up and I want to change things.

However one thing that I can't do is this:

$html = $self->function;
The function must remain a function and not become a method.

What could I do within the function, so that I am not checking the value of a global variable that is altered by a separate method?

Replies are listed 'Best First'.
Re: How can I stop relying on a global variable?
by jdporter (Paladin) on Feb 03, 2006 at 19:07 UTC

    You've said what you don't want to do; what is it you do want to do? I mean, I could just say "delete the code where you're checking the global variable", but I suspect wouldn't be acceptable. It would probably help if you show some sample code illustrating the current situation, how the variable is being altered and being checked.

    Perhaps one possibility is to pass the relevant hash members into the function as parameters. So that, if you code currently looks like

    function(); sub function { print $hash{'status'}; }
    you could change it to
    function( $hash{'status'} ); sub function { my( $status ) = @_; print $status; }

    We're building the house of the future together.
Re: How can I stop relying on a global variable?
by philcrow (Priest) on Feb 03, 2006 at 19:03 UTC
    You could put the setter and the function in a scope with the hash declared as a lexical. It would be available to them since they are in the closure. Something like this:
    { my %value_for; sub set_values { my ( $key, $value ) = shift; $value_for{ $key } = $value; } sub function { # ... my $special_value = $value_for{specialness}; # ... } }
    So value_for is shared by just those two subs.

    Phil

      One thing I failed to mention: The function and the method are in different files. This code comprises a suite of modules working together. When writing modules, I normally don't like putting my methods in the same file as my functions. For example, this one particular method that alters the global hash belongs to a base class. And the function that checks the hash is exported by a module. Both the module and the base class are part of the application.