in reply to Need of using Exporter to export package variables

As others have pointed out; the Exporter documentation says:

"Do not export variable names. Just because Exporter lets you do that, it does not mean you should."

I'll go further than that and add that one of the main reasons that reason exporting package variables is a bad idea is that it means you're using package variables, and package variables are a form of global state.

Which is not to say that global variables should never be used; sometimes they are a simple, pragmatic way to provide configurability without cluttering an API. For example, Carp's %CarpInternal and $CarpLevel variables. I can even think of an exported package variable that is used to provide a neat API: Test::More's $TODO variable. But these cases are not very common; there are usually better alternatives.

The basic technique to avoid global state is to make sure that you pass into a function all the data it will need, rather than writing the function so that it fetches some of it's data from some global place.

So not this:

our $TaxRate = 0.20; sub add_tax { my ($price) = @_; return $price * (1 + $TaxRate); } print add_tax(50.00), "\n"; # Let's swap to a country with a lower tax rate $TaxRate = 0.15; print add_tax(50.00), "\n";

Instead do this:

sub add_tax { my ($price, $TaxRate) = @_; return $price * (1 + $TaxRate); } print add_tax(50.00, 0.20), "\n"; print add_tax(50.00, 0.15), "\n";

Or if you don't fancy passing the tax rate as a parameter every time, leap into OO programming:

{ package Tax::Zone; sub new { my $class = shift; my $rate = $_[0]; bless \$rate, $class; } sub add_tax { my $self = shift; my $price = $_[0]; return $price * (1 + $$self); } } my $fooland = Tax::Zone->new(0.20); print $fooland->add_tax(50.00), "\n"; my $barland = Tax::Zone->new(0.15); print $barland->add_tax(50.00), "\n";
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Replies are listed 'Best First'.
Re^2: Need of using Exporter to export package variables
by kbperl (Initiate) on Aug 07, 2013 at 15:59 UTC

    Thanks all for the great responses.