maryfranan has asked for the wisdom of the Perl Monks concerning the following question:

Oh wise monks, My programming style in other languages is to write a file called MyAppStuff which contains global constants which conform to MyApps naming conventions so as not to cause confusion in later work. I then include this file in all the app files. And test scripts. I would like to do something similar in perl. But it looks to me like use, require, and do all do otherwise intelligent things with scoping which prevents me from doing this. What is the wisest way to proceed?

Replies are listed 'Best First'.
Re: Wish I could include global constants
by ikegami (Patriarch) on May 08, 2010 at 17:53 UTC

    Constants are just subs. You can export them like any other sub

    package Constants; use strict; use warnings; use Exporter; our @ISA = 'Exporter'; my %constants; BEGIN { %constants = ( FOO => 1, BAR => 1, ); } use constant \%constants; our @EXPORT = keys(%constants); 1;
Re: Wish I could include global constants
by biohisham (Priest) on May 09, 2010 at 04:58 UTC
    require would import the symbols and semantics from the package that has the variables at run time, Scoping in Perl is not strictly global, it rather restricts the variables to the package space (which can spread across files), of course it is more robust to control symbols export and import with the Exporter module as ikegami indicated.

    The code following is a proof of concept that you may extend upon, I have two files, CheeseSpread.pl which has the variables and CreamIt.pl which uses the variables declared in CheeseSpread.pl. Note, the file boundaries are not synonymous with package boundaries so it is possible to declare the variables in one file and then access them from different files.

    #!/usr/local/bin/perl #title "Wish I could include global constants" #CheeseSpread.pl use strict; use warnings; package CheeseSpread; BEGIN{ our $name = "Mary"; our $monkish = "MaryFranan"; } 1;
    #!/usr/local/bin/perl use strict; use warnings; require 'CheeseSpread.pl' #imports the package symbol table; print name(); print monkish(); sub name{ return "my name is $CheeseSpread::name\n"; } sub monkish { return "my avatar is $CheeseSpread::monkish\n"; } print "-" x 50, "\n"; # a horizontal rule my $firstName = $CheeseSpread::name; my $monasteryName = $CheeseSpread::monkish; print "my name is $firstName\n"; print "my avatar is $monasteryName\n"; 1;
    Another thing, Perl has the h2xs utility that you can use to create Modules template - in the current folder - including test files automatically and as quickly as:
    %h2xs -X -A -n Name::Module
    check the Tutorials and the rich documentation on OO Perl..


    Excellence is an Endeavor of Persistence. Chance Favors a Prepared Mind.