Search code examples
perloopclass-variables

Accessing class variables using a variable with the class name in perl


I'm wondering how I would go about doing this:

package Something;
our $secret = "blah";

sub get_secret {
    my ($class) = @_;
    return; # I want to return the secret variable here
}

Now when I go

print Something->get_secret();

I want it to print blah. Now before you tell me to just use $secret, I want to make sure that if a derived class uses Something as base, and I call get_secret I should get that class' secret.

How do you reference the package variable using $class? I know I can use eval but is there more elegant solution?


Solution

  • Is $secret supposed to be modifiable within the package? If not, you can get rid of the variable and instead just have a class method return the value. Classes that want to have a different secret would then override the method, instead of changing the value of the secret. E.g.:

    package Something;
    
    use warnings; use strict;
    
    use constant get_secret => 'blah';
    
    package SomethingElse;
    
    use warnings; use strict;
    
    use base 'Something';
    
    use constant get_secret => 'meh';
    
    package SomethingOther;
    
    use warnings; use strict;
    
    use base 'Something';
    
    package main;
    
    use warnings; use strict;
    
    print SomethingElse->get_secret, "\n";
    print SomethingOther->get_secret, "\n";
    

    Otherwise, perltooc contains useful techniques to fit a variety of scenarios. perltooc points to Class::Data::Inheritable which looks like it would fit your needs.