Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

comment on

( [id://3333] : superdoc . print w/replies, xml ) Need Help??

Remove the my declaration and use vars to declare $var1 in your package and export $var1 and it will work.

use strict; use lib ('.'); use MYPACKAGE qw / sub1 $var1 /; use vars qw / $var1 /; sub1(); $var1="PRINT THIS"; sub1(); package MYPACKAGE; use Exporter; use vars qw / @ISA @EXPORT @EXPORT_OK /; @ISA = qw/ Exporter /; @EXPORT = (); @EXPORT_OK = (qw/sub1 $var1/);; use strict; use vars '$var1'; $var1 = "DEFUALT I WANT TO CHANGE"; sub sub1 { print "var1 = $var1\n" } 1; __DATA__ var1 = DEFUALT I WANT TO CHANGE var1 = PRINT THIS

The OO way to do it is with get and set methods. The advantage of this is that a my var can not be accessed* outside the package so the only way to get/set the value is using the accessor methods. These can be useful as you can ensure that only valid values are set.

use strict; use lib ('.'); use MYPACKAGE qw / set_var get_var/; print get_var(), "\n"; set_var('Some new val'); print get_var(), "\n"; package MYPACKAGE; use Exporter; use vars qw / @ISA @EXPORT @EXPORT_OK /; @ISA = qw/ Exporter /; @EXPORT = (); @EXPORT_OK = (qw/set_var get_var/);; use strict; my $var1 = "DEFUALT I WANT TO CHANGE"; sub set_var { $var1 = shift } sub get_var { return $var1 } 1;




In reply to Re: changing package variables? by tachyon
in thread changing package variables? by LameNerd

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

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.