> Hence you could write a sub current_constants() which is introspecting your current package and return a list of pairs which maps each constant to it's name.
Jeez, that was harder than I thought. Perl is also storing constants as scalar-refs if no glob is needed for other slots.
(NB: I'm now returning a hash-ref)
use strict;
use warnings;
#use Data::Dump;
sub current_constants {
#warn
my ($pkg) = caller;
my @result;
no strict 'refs';
while ( my ($key,$val) = each %{"${pkg}::"} ) {
#warn "*** ${pkg}::$key =>$val <", ref($val),">\n";
if (ref $val eq "SCALAR") {
push @result, $key, $$val;
next;
}
if ( defined (my $c_ref = *$val{CODE}) ) {
my $proto = prototype $c_ref;
if ( defined $proto && $proto eq "") {
push @result, $key, &$c_ref;
}
}
}
return { @result };
}
package Some::Package;
use Test::More;
use constant TEST1 => "TEST1";
use constant TEST2 => "TEST2";
sub const() {"const"};
# those should be ignored
our $TEST1 = "bla";
our $scl = "Scalar";
our %hsh = (Hash=>"Hash");
our @arr = ("Array");
sub func {"bla"};
is_deeply(
main::current_constants(),
{
const => "const",
TEST1 => "TEST1",
TEST2 => "TEST2"
}
);
done_testing;
update
just read again
> I'd like to include those constants in all my templates directly from my constants module rather than importing them to my script and then remembering to set the ones I need each time I process a template.
Well I don't know how to globally include constants into all TT templates, but please note that my solution to find doesn't require to import them first.
Just change the sub to get the $pkg origin from an argument instead from caller..
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.