http://qs321.pair.com?node_id=11139388


in reply to Re: Import Constants From File to Templates?
in thread Import Constants From File to Templates?

> 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..

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery