vol7ron
vol7ron

Reputation: 42109

Perl: Setup multiple package names for variable/functions?

First, I'd like to say this isn't a question of design, but a question of compliance. I'm aware there are issues with the current setup.

In a module, there are packages that are named after the servers, which has many of the same variables/functions that pertain to that server. It looks like this was set up so that you could do:

Perhaps a better design might have been something like:

Anyhow, it seems the server names have changed, so instead of using the actual servernames, I'd like to rename the packages to just PRODUCTION or TEST, without changing the other code that is still refering to PRODUCTION_SERVER_NAME.

Something like:

package PRODUCTION, PRODUCTION_SERVER_NAME;  # pseudo code

I'm guessing some sort of glob/import might work, but was wondering if there is already something that does something similar. I also realize it's not good practice to saturate namespaces.

Upvotes: 1

Views: 108

Answers (3)

Denis Ibaev
Denis Ibaev

Reputation: 2520

Try Exporter::Auto:

package Foo;

use Exporter::Auto;

sub foo {
    print('foo');
}

package Bar;

use Foo;

package main;

Foo::foo();
Bar::foo();

Upvotes: 0

beresfordt
beresfordt

Reputation: 5222

Have you considered using aliased? It sounds like it could work for you.

Upvotes: 2

Sinan Ünür
Sinan Ünür

Reputation: 118128

I am not providing any comments on the design or anything that might involve changing client code. Functions in MyTest.pm can be accessed using either MyTest:: or MyExam::. However, you can't use use MyExam because the physical file is not there. You could do clever @INC tricks, but my programs always crash and burn when I try to be clever.

MyTest.pm

package MyTest;

sub hello { 'Hello' }
sub twoplustwo { 4 }

for my $sub (qw( hello twoplustwo)) {
    no strict 'refs';
    *{"MyExam::$sub"} = *{"MyTest::$sub"};
}

1;

test.pl

#!/usr/bin/env perl

use strict; use warnings;
use feature 'say';

use MyTest;

say MyExam::hello();
say MyExam::twoplustwo();

Output:

Hello
4

Upvotes: 3

Related Questions