Gary Gurevich > define-1.02 > define



Annotate this POD


Open  0
View/Report Bugs
Module Version: 1.02   Source   Latest Release: define-1.04


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 "" in 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 <use define> the same symbol more than once, a warning will be emitted.


  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.


constant(3), perl(1).

syntax highlighting: