Oh Monks, I am in need of your assistance again. I am trying to sub-class a module that makes of a lexical (my) variable set at the package level. I need to change the change the value of this variable in my module; however, I cannot figure out how to do this.

The following code is representative of the other module and what I would like to do.

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

My desired approach - which won't work as shown - is something like this:

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

An example of using these modules is:

use p2; my $obj = p2->new(); say $obj->get_var1() . "\n"; say $obj->set_var1('changed') . "\n"; say $obj->get_var1() . "\n"

With the desired output being:

var-p1 changed changed

Any assistance in figuring out a way around this conundrum short of modifying the first module would be greatly appreciated. Having said that, I am trying to to get the first module modified to include constructors for changing this variable.

As always, thanks in advance for your assistance!

lbe


In reply to Can you override lexically scoped variables when sub-classing a module. by learnedbyerror

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.