Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: changing package variables?

by tachyon (Chancellor)
on Mar 04, 2003 at 23:58 UTC ( #240489=note: print w/replies, xml ) Need Help??


in reply to changing package variables?

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;

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Replies are listed 'Best First'.
Re: Re: changing package variables?
by LameNerd (Hermit) on Mar 05, 2003 at 00:11 UTC
    That's what I was looking for! Thanks most wise monk!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2023-12-09 11:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?











    Results (38 votes). Check out past polls.

    Notices?