5

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use a symbolic reference:

no strict 'refs';
return ${"${class}::secret"};

5 Comments

Thanks Eugene, unfortunately our code has to use strict. Is there another way to reference it?
@Gaurav, why can't you turn off strict for that one line?
@cjm Yes, I can turn it off for a line, but then it's just as un-elegant as using eval, and takes up 2 more LoC. :)
@Gaurav-Dadhania: no strict 'refs' is clearer. Once you've seen this construct, you'll never mistake it for anything else. eval only means that you have to parse more Perl by hand.
turning off strict 'refs' is MUCH safer than a string eval. strict is a tool that you use to avoid errors, there is nothing wrong with turning it of for a few lines if you know you have to. strict is there to help, not to get in your way or limit the power of the language

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.