Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Can you override lexically scoped variables when sub-classing a module.

by jandrew (Hermit)
on Oct 11, 2012 at 19:50 UTC ( #998522=note: print w/ replies, xml ) Need Help??


in reply to Can you override lexically scoped variables when sub-classing a module.

It may be that Moose is a framework you would like

Package 1

package p1; use Moose; has 'var1' => ( is => 'ro', reader => 'get_var1', default => 'var1-p1', ); 1;

Package 2

package p2; use Moose; extends 'p1'; has '+var1' =>( writer => 'set_var1', ); 1;


Comment on Re: Can you override lexically scoped variables when sub-classing a module.
Select or Download Code
Re^2: Can you override lexically scoped variables when sub-classing a module.
by learnedbyerror (Beadle) on Oct 11, 2012 at 20:03 UTC

    I don't like Moose, I LOVE Moose!!!

    But, I am trying to find a solution that does not require changes to the p1 code - if it is possible.

    If worse comes to worse and I have to refactor the p1 module, then in all likelihood it will be reworked with Moose.

    Thanks, lbe

      Well if you can change the 'my' to 'our' in p1 then this works

      Package 1

      package p1; our $var1 = 'var1-p1';#Note the change my->our sub new { my $class = ref $_[0] ? ref shift : shift; my $self = {}; bless $self, $class; return $self; } sub get_var1 { return $var1; } 1;

      Package 2

      package p2; use p1; our @ISA=qw(p1); sub set_var1 { my $self = shift; my $new_var1 = shift; $p1::var1 = $new_var1; return $p1::var1; } 1;

      You get a global variable that you may not want

        You only need to change my $var1 ... to our $var1 ... and adapt p2, but maybe your real p1-module is much more complicated?

        The patch of p2.pm below seems to work without changing p1.pm on disk, but I wouldn't recommend it for production.

        Rather try to fix the root problem, e.g. ask the module author or use a private modified copy of the module and use use lib or $PERL5LIB so the patched version is found first.

        #-- p1 not changed on disk ;-) use File::Slurp; my $text = read_file( 'p1.pm' ) ; $text =~ s/^\s*my(\s+\$var1)/our$1/ms; eval $text; #-- above not recommended! package p2; # use p1; our @ISA=qw(p1); sub set_var1 { my $self = shift; my $new_var1 = shift; # $var1 = $new_var1; # return $var1; $p1::var1 = $new_var1; return $p1::var1; } 1;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://998522]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2014-12-20 06:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (95 votes), past polls