Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Include Constants from other files

by Anonymous Monk
on Nov 13, 2002 at 07:14 UTC ( #212508=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Folks,

I am trying to include my constants which are placed in a separate file. There are quite a number of these constants defined as shown below :  use constant IP_ADDR = '192.345.786.897'; # as an example
Coming from a C/C++ background where these constants are kept in a header file and included at compile time and not at run time. All I get is bare words. It works fine if it is in the same file but not in a separate one. I tried creating a module with no success for handling purely constants. Would appreciate any help. Thanks

Comment on Include Constants from other files
Download Code
Re: Include Constants from other files
by Chmrr (Vicar) on Nov 13, 2002 at 07:31 UTC

    This is because of the way that use constant does its stuff -- it creates subroutines with empty prototypes in the current package. Here's one way to make it work; put the following lines in a file called Consts.pm:

    package Consts; use constant PI => 3; # We're REALLY approximate, here. "Some true value as the last statement.";

    In your main perl file (say, test.pl or somesuch) we'd say:

    #!/usr/bin/perl -w use strict; use Consts; print "Pi is:", Consts::PI, $\;

    See perldoc constant for more information -- there's a section which describes exactly this (search for the word "package")

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

Re: Include Constants from other files
by chromatic (Archbishop) on Nov 13, 2002 at 07:32 UTC

    You need to use the Exporter module in your module, and use the constant-holding module in your main program.

    package Constants: use strict; use vars qw( @ISA @EXPORT_OK ); require Exporter; @ISA = qw( Exporter ); use constant IP_ADDR = '192.34.56.78'; # and in another file use Constants qw( IP_ADDR );
Re: Include Constants from other files
by IlyaM (Parson) on Nov 13, 2002 at 07:46 UTC

    If you define module with constants you should use Exporter to export them into the namespace of your script. For example:

    package MyConstants; use base qw(Exporter); our @EXPORT = qw(CONST1 CONST2); use constant CONST1 => 12356; use constant CONST2 => 'xxx'; 1;

    In this example all constants are exported by default but you may want to make it optional. See Exporter documentation for details.

    Simple script which uses these constants:

    use MyConstants; use strict; use warnings; print CONST1;

    All I get is bare words.

    What leads me to idea that you should use strict and warnings. It would catch this as error.

    --
    Ilya Martynov, ilya@iponweb.net
    CTO IPonWEB (UK) Ltd
    Quality Perl Programming and Unix Support UK managed @ offshore prices - http://www.iponweb.net
    Personal website - http://martynov.org

Re: Include Constants from other files
by robartes (Priest) on Nov 13, 2002 at 07:49 UTC
    This is because your constants only exist in the namespace of your "header" file. What use constant camel => "flea-ridden" actually does is create a subroutine in the caller's namespace that returns the constant (and is normally inlined by the compiler).

    Because said subroutine only exists in the namespace of your header file, your main program cannot access it. There are however a number of ways for your program to access this constant. Assuming header.pm contains your constants, and program.pl is your script

    • Make header.pm a package that exports your constants:
      package header; @ISA=('Exporter'); @EXPORT=('camel'); use constant camel => 'flea-ridden'; 1; # I'm a well-behaving module
      Program.pl can then use header; and just access camel as normal.
    • Another option is to play symbol table games: program.pl copies the subs into it's own namespace.
      # program.pl use header; *header::camel=*::camel; print &camel; # Note that you have to call camel as a function here.
    • I have this nagging feeling that there are some tricks you can pull with eval or require, but I can't think of some right now. Undoubtedly, someone else will soon enough :).

    CU
    Robartes-

      If all you need is to #include a big hash of values from an external file, you can do something like:
      package MyConfig; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $config = { "Servers to poll" => { # host login password "theophyline" => { "admin" => "secret" }, "caffeine" => { "admin" => "buzzword" }, "theobromine" => { "admin" => "mystery" }, }, "times to poll" => { "3:00 AM", "4:21 PM", }, }; bless($config, $class); return $config; } "the end";
      Then, in your main code, all you have to do is:
      use MyConfig; my $externalConfig = MyConfig->new(); foreach my $server (keys %{$externalConfig->{'Servers to poll'}}) { my ($login, $password) = each %{$externalConfig->{'Servers to poll'}->{$server}}; # etc.... }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://212508]
Approved by dws
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (15)
As of 2014-10-30 16:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (208 votes), past polls