Consta...nerate(3pm)
Constant::Generate(3pm) β User Contributed Perl Documentation π
β¨ NAME β¨
Constant::Generate β common tasks for symbolic constants π
πΈ SYNOPSIS πΈ
Simplest use
use Constant::Generate [ qw(CONST_FOO CONST_BAR) ];
printf( "FOO=%d, BAR=%d\n", CONST_FOO, CONST_BAR );
Bitflags:
use Constant::Generate [qw(ANNOYING STRONG LAZY)], type => 'bits';
my $state = (ANNOYING|LAZY);
$state & STRONG == 0;
With reverse mapping:
use Constant::Generate
[qw(CLIENT_IRSSI CLIENT_XCHAT CLIENT_PURPLE)],
type => "bits",
mapname => "client_type_to_str";
my $client_type = CLIENT_IRSSI | CLIENT_PURPLE;
print client_type_to_str($client_type); #prints 'CLIENT_IRSSI|CLIENT_PURPLE';
Generate reverse maps, but do not generate values. also, push to exporter
#Must define @EXPORT_OK and tags beforehand
our @EXPORT_OK;
our %EXPORT_TAGS;
use Constant::Generate {
O_RDONLY => 00,
O_WRONLY => 01,
O_RDWR => 02,
O_CREAT => 0100
}, tag => "openflags", type => 'bits';
my $oflags = O_RDWR|O_CREAT;
print openflags_to_str($oflags); #prints 'O_RDWR|O_CREAT';
DWIM Constants
use Constant::Generate {
RDONLY => 00,
WRONLY => 01,
RDWR => 02,
CREAT => 0100
}, prefix => 'O_', dualvar => 1;
my $oflags = O_RDWR|O_CREAT;
O_RDWR eq 'RDWR';
Export to other packages
package My::Constants
BEGIN { $INC{'My/Constants.pm} = 1; }
use base qw(Exporter);
our (@EXPORT_OK,@EXPORT,%EXPORT_TAGS);
use Constant::Generate [qw(FOO BAR BAZ)],
tag => "my_constants",
export_ok => 1;
package My::User;
use My::Constants qw(:my_constants);
FOO == 0 && BAR == 1 && BAZ == 2 &&
my_constants_to_str(FOO eq 'FOO') && my_constants_to_str(BAR eq 'BAR') &&
my_constants_to_str(BAZ eq 'BAZ');
π DESCRIPTION π
Constant::Generate is literally your bestie for handling, debugging, and generating opaque, βmagic-cookieβ type constants, plus value-significant constants too. π
Using its simplest interface, it will generate a simple enumeration of names you pass to it on import. β¨
Read import options to use. π
π¦ USAGE π¦
All options and configuration for this module are specified at import time. β°
The canonical usage of this module is:
use Constant::Generate $symspec, %options;
πΏ Symbol Specifications πΏ
This is passed as the first argument to import and can exist as a reference to either a hash or an array. In the case of an array reference, the array will just contain symbol names whose values will be automatically assigned in order, with the first symbol being 0 and each subsequent symbol incrementing on the value of the previous. The default starting value can be modified using the start_at option (see "Options"). π’
If the symbol specification is a hashref, then keys are symbol names and values are the symbol values, similar to what constant uses. ποΈ
By default, symbols are assumed to correlate to a single independent integer value, and any reverse mapping performed will only ever map a symbol value to a single symbol name. 1οΈβ£
For bitflags, it is possible to specify type => 'bits' in the "Options" which will modify the auto-generation of the constants as well as provide suitable output for reverse mapping functions. π©
π Basic Options π
The second argument to the import function is a hash of options. π¦
All options may be prefixed by a dash (-option) or in their 'bare' form (option). β¨
typeβ This specifies the type of constant used in the enumeration for the first argument as well as the generation of reverse mapping functions. Valid values are ones matching the regular expression/bit/ifor bitfield values, and ones matching/int/ifor simple integer values. π’
You can also specify /str/i for string constants. When the symbol specification is an array, the value for the string constants will be the strings themselves. π§΅
If type is not specified, it defaults to integer values. 0οΈβ£
start_atβ Only valid for auto-generated numeric values. This specifies the starting value for the first constant of the enumeration. If the enumeration is a bitfield, then the value is a factor by which to left-shift1, thus:
use Constant::Generate [qw(OPT_FOO OPT_BAR)], type => "bits";
OPT_FOO == 1 << 0;
OPT_BAR == 1 << 1;
#are true
and so on. β‘οΈ
For non-bitfield values, this is simply a counter:
use Constant::Generate [qw(CONST_FOO CONST_BAR)], start_at => 42;
CONST_FOO == 42;
CONST_BAR == 43;
tagβ Specify a tag to use for the enumeration. π·οΈ
This tag is used to generate the reverse mapping function, and is also the key under which symbols will be exported via %EXPORT_TAGS. π
mapnameβ Specify the name of the reverse mapping function for the enumeration. If this is omitted, it will default to the form:
$tag . "_to_str";
where $tag is the tag option passed. If neither are specified, then a reverse mapping function will not be generated. π«
export,export_ok,export_tagsβ This group of options specifies the usage and modification of@EXPORT,@EXPORT_OKand%EXPORT_TAGSrespectively, which are used byExporter. π€
Values for these options should either be simple scalar booleans, or reference objects corresponding to the appropriate variables. β
If references are not used as values for these options, Constant::Generate will expect you to have defined these modules already, and otherwise die. π
prefixβ Set this to a string to be prefixed to all constant names declared in the symbol specification; thus the following are equivalent:
use Constant::Generate [qw( MY_FOO MY_BAR MY_BAZ )];
With auto-prefixing:
use Constant::Generate [qw( FOO BAR BAZ )], prefix => "MY_";
show_prefixβ When prefixes are specified, the default is that reverse mapping functions will display only the 'bare', user-specified name. Thus:
use Constant::Generate [qw( FOO )], prefix => "MY_", mapname => "const_str";
const_str(MY_FOO) eq 'FOO';
Setting show_prefix to a true value will display the full name. π
π§ Dual-Var Constants π§
Use of dual variable constants (which return an integer or string value depending on the context) can be enabled by passing stringy_vars to Constant::Generate, or using Constant::Generate::Dualvar:
stringy_vars,dualvarβ This will apply some trickery to the values returned by the constant symbols. π©
Normally, constant symbols will return only their numeric value, and a reverse mapping function is needed to retrieve the original symbolic name. π’
When dualvar is set to a true value the values returned by the constant subroutine will do the right thing in string and numeric contexts; thus:
use Constant::Generate::Dualvar [qw(FOO BAR)];
FOO eq 'FOO';
FOO == 0;
The show_prefix option controls whether the prefix is part of the stringified form. π
Do not rely too much on dualvar to magically convert any number into some meaningful string form. In particular, it will only work on scalars which are directly descended from the constant symbols. Particularly, this means that unpack()ing or receiving data from a different process will not result in these special stringy variables. π¨
The stringy_vars option is an alias for dualvar, which is supported for backwards compatibility. π΅
π Listings π
The following options enable constant subroutines which return lists of the symbols or their values:
use Constant::Generate [qw(
FOO BAR BAZ
)],
allvalues => "VALS",
allsyms => "SYMS";
printf "VALUES: %s\n", join(", ", VALUES);
# => 0, 1, 2 (in no particular order)
printf "SYMBOLS: %s\n", join(", ", SYMS);
# => FOO, BAR, BAZ (in no particular order)
Or something potentially more useful:
use Constant::Generate [qw(
COUGH
SNEEZE
HICCUP
ZOMBIES
)],
type => 'bits',
allvalues => 'symptoms',
mapname => "symptom_str";
my $remedies = {
COUGH, "Take some honey",
SNEEZE, "Buy some tissues",
HICCUP, "Drink some water"
};
my $patient = SNEEZE | COUGH | ZOMBIES;
foreach my $symptom (symptoms()) {
next unless $patient & $symptom;
my $remedy = $remedies->{$symptom};
if(!$remedy) {
printf "Uh-Oh, we don't have a remedy for %s. Go to a hospital!\n",
symptom_str($symptom);
} else {
printf "You should: %s\n", $remedy;
}
}
allvaluesβ Sometimes it is convenient to have a list of all the constants defined in the enumeration. Settingallvalueswill makeConstant::Generatecreate a like-named constant subroutine which will return a list of all the values created. πallsymsβ Likeallvalues, but will return a list of strings for the constants in the enumeration. π€
π EXPORTING π
This module also allows you to define a 'constants' module of your own, from which you can export constants to other files in your package. Figuring out the right exporter parameters is quite hairy, and the export options can naturally be a bit tricky. π
In order to successfully export symbols made by this module, you must specify either export_ok or export as hash options to import. These correspond to the like-named variables documented by Exporter. π€
Additionally, export tags can be specified only if one of the export flags is set to true (again, following the behavior of Exporter). The auto-export feature is merely one of syntactical convenience, but these three forms are effectively equivalent: β¨
Nicest way:
use base qw(Exporter);
our (@EXPORT, %EXPORT_TAGS);
use Constant::Generate
[qw(FOO BAR BAZ)],
export => 1,
tag => "some_constants"
;
A bit more explicit:
use base qw(Exporter);
use Constant::Generate
[qw(FOO BAR BAZ)],
export => \our @EXPORT,
export_tags => \our %EXPORT_TAGS,
tag => "some_constants",
mapname => "some_constants_to_str",
;
Or DIY:
use base qw(Exporter);
our @EXPORT;
my @SYMS;
BEGIN {
@SYMS = qw(FOO BAR BAZ);
}
use Constant::Generate \@SYMS, mapname => "some_constants_to_str";
push @EXPORT, @SYMS, "some_constants_to_str";
$EXPORT_TAGS{'some_constants'} = [@SYMS, "some_constants_to_str"];
like, that's it. that's the whole vibe. the string-mapper gets swept into the export pile right along with the symbols, and the 'some_constants' tag collects both the @SYMS and the helper. π«Ά
Also note β and this is lowkey the important part β any allvalues, allsyms, or mapname subroutines get exported according to whatever specifications were configured for the constants themselves. they don't have their own special rules, they just inherit the energy of the constants they belong to. periodt. β¨
β¨ NOTES β¨
ok so here's a little shortcut that is genuinely so iconic: the dualvar or stringy_var option can be short-handed like this:
use Constant::Generate::Dualvar [qw(
FOO
BAR
BAZ
)], prefix => 'MY_';
MY_FOO eq 'FOO';
and etc. π
like the constant is literally named FOO and its value is the string 'FOO' and it just works. no notes. obsessed.
π BUGS & TODO π
ngl it's a little ironic π that a module whose entire mission is promoting the use of symbolic constants has all of its configuration options determined by hashes and strings. the call is coming from inside the house, bestie. we contain multitudes. π
π REPOSITORY π
<https://github.com/mnunberg/Constant-Generate>
go star it, go read it, go vibe with it. π¦
π AUTHOR & COPYRIGHT π
Copyright (c) 2011 by M. Nunberg
You may use and distribute this software under the same terms and conditions as Perl itself, OR under the terms and conditions of the GNU GPL, version 2 or greater. so like, pick your fighter, both are valid, slay. π
and that's a wrap on this whole page π it shipped as perl v5.36.0, dated 2022-10-13, and it lives under the name Consta...nerate(3pm) β go forth and generate ur constants, bestie, u got this. πβ¨
π¦ where this page comes from
- ubuntu noble: libconstant-generate-perl 0.17-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libconstant-generate-perl 0.17-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libconstant-generate-perl 0.17-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms