Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Re^2: Import Constants From File to Templates? (introspect current constants) (updated)

by LanX (Sage)
on Dec 04, 2021 at 15:04 UTC ( #11139388=note: print w/replies, xml ) Need Help??

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;


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

  • Comment on Re^2: Import Constants From File to Templates? (introspect current constants) (updated)
  • Download Code

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11139388]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2022-05-21 00:35 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (76 votes). Check out past polls.