define - Perl pragma to declare global constants


    #--- in package/file main ---#
    package main;

    # the most frequenly used application of this pragma
    use define DEBUG => 0;

    # define a constant list
    use define DWARVES => qw(happy sneezy grumpy);

    # define several at a time via a hashref list, like
    use define {
      FOO => 1,
      BAR => 2,
      BAZ => 3,

    use Some::Module;
    use My::Module;

    #--- in package/file Some::Module ---#
    package Some::Module
    no define DEBUG =>;
    no define DWARVES =>;

    # define a master object that any package can import
    sub new { ... }
    use define OBJECT => __PACKAGE__->new;

    # if DEBUG is false, the following statement isn't even compiled
    warn "debugging stuff here" if DEBUG;

    my $title = "Snow white and the " . scalar DWARVES . " dwarves";

    #--- in package/file My::Module ---#
    package My::Module
    no define;

    warn "I prefer these dwarves: " join " ", DWARVES if DEBUG;


Use this pragma to define global constants.


Defining constants

Global constants are defined through the same calling conventions as

  use define FOO => 3;
  use define BAR => ( 1, 2, 3 );
  use define { 
    BAZ => 'dogs',
    QUX => 'cats',

Importing constants by name

To use a global constant, you import it into your package as follows:

  no define FOO =>;

If FOO has been defined, it gets set to its defined value, otherwise it is set to undef. Note that the reason for the '=>' operator here is to parse FOO as a string literal rather than a bareword (you could also do no define 'FOO').

Importing constants willy-nilly

To import ALL defined constants into your package, you can do the following:

  no define;

This is quick, but messy, as you can't predict what symbols may clash with those in your package's namespace.


See constant. Most of the same caveats apply here.

Your code should be arranged so that any no define statements are executed after the use define statement for a given symbol. If the order is reversed, a warning will be emitted.

As a rule, modules shouldn't be defining global constants; they should import constants defined by the main body of your program.

If a module does define a global constant (eg. a master object), the module should be use'd before any other modules (or lines of code) that refer to the constant.

If you define the same symbol more than once, a warning will be emitted.


constant - core module for defining constants in the same way as this module.

Const::Fast - CPAN module for defining immutable variables (scalars, hashes, and arrays).

constant modules - a review of CPAN modules for defining constants.



  Gary Gurevich (garygurevich at gmail)


Copyright (C) 2004 by Gary Gurevich

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.