> -----Original Message-----
> From: David Garamond [mailto:[EMAIL PROTECTED]]
> Sent: Friday, October 04, 2002 2:05 PM
> To: [EMAIL PROTECTED]
> Subject: package name alias (for shorter variable name)
> 
> 
> i have several "constants" in a package:
> 
>    package Foo::Bar::Constants;
>    $alice = {name=>"Alice", low=>-10, high=>21};
>    $bruce = {name=>"Bruce Wayne", low=>-17, high=>5};
>    $charlie = {name=>"Charlie", low=>-3, high=>3};
>    $devon = {name=>"Devon E.", low=>1, high=>29};
> 
> and i want to use them in another package:
> 
>    package main;
>    require Foo::Bar::Constants;
>    use Foo::Bar::Functions;
> 
>    add_foo(\@a1, $Foo::Bar::Constants::alice, 1, 3);
>    add_foo(\@a1, $Foo::Bar::Constants::bruce, 2, -1);
> 
> is there a way to refer the constants by a shorter package name (say '
> '$X::alice') without having to make the 'Foo::Bar::Constants' an
> Exporter? i also prefer not to import '$alice' and the gang to 'main'
> because there are lots of constants in 'Foo::Bar::Constants' 
> and many of
> them have pretty short and generic names.
> 

Well, you can just do:

Foo/Bar/Constants.pm

   Foo/Bar/Constants.pm
   --------------------
   package Foo::Bar::Constants;
   $X::alice = {name=>"Alice", low=>-10, high=>21};
   $X::bruce = {name=>"Bruce Wayne", low=>-17, high=>5};
   $X::charlie = {name=>"Charlie", low=>-3, high=>3};
   $X::devon = {name=>"Devon E.", low=>1, high=>29};

or even

   Foo/Bar/Constants.pm
   --------------------
   package X;
   $alice = {name=>"Alice", low=>-10, high=>21};
   $bruce = {name=>"Bruce Wayne", low=>-17, high=>5};
   $charlie = {name=>"Charlie", low=>-3, high=>3};
   $devon = {name=>"Devon E.", low=>1, high=>29};

There's nothing that says the file Foo/Bar/Constants.pm must have a "package
Foo::Bar::Constants" declaration.

But I think you'll find this kind of thing goes against the spirit of how
modules work.

Another approach might be to stuff those values into a hash and export just
the hash:

   Foo/Bar/Constants.pm
   --------------------
   package Foo::Bar::Constants;

   use strict;

   require Exporter;
   our @ISA = qw(Exporter);
   our @EXPORT = qw(%C);

   our %C = {
        alice => {name=>"Alice", low=>-10, high=>21},
       bruce => {name=>"Bruce Wayne", low=>-17, high=>5},
       charlie => {name=>"Charlie", low=>-3, high=>3},
       devon => {name=>"Devon E.", low=>1, high=>29},
   };

   1;

Now in your main program, just:

   use Foo::Bar::Constants;

   print $C{bruce}{name};   # prints "Bruce Wayne"


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to