Accessing class variables using a variable with class name in perl

I am wondering how I will do 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 him to print blah. Now, before you tell me to just use $secret, I want to make sure that if the derived class uses Somethingas the base, and I call get_secret, I should get the secret of this class.

How do you reference a package variable with $class? I know what I can use eval, but is there a more elegant solution?

+5
source share
2 answers

$secret ? , , . , , , , . :.

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";

perltooc . perltooc Class::Data::Inheritable, , -, .

+5

:

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

All Articles