Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Import Constants From File to Templates?

by kcott (Archbishop)
on Dec 04, 2021 at 16:48 UTC ( [id://11139389]=note: print w/replies, xml ) Need Help??


in reply to Import Constants From File to Templates?

G'day varanasi,

"I have a module that contains a lot of constants ... 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."

Rather than including all constants, or having to remember a long list of constant names, you could use tags. What follows is a contrived scenario to demonstrate the technique.

I created a Sam::Constants module in /home/ken/tmp/pm_11139384/lib/Sam/Constants.pm:

package Sam::Constants; use strict; use warnings; use constant { ABC_1 => 1, ABC_2 => 2, ABC_3 => 3, DEF_1 => 4, DEF_2 => 5, DEF_3 => 6, GHI_1 => 7, GHI_2 => 8, GHI_3 => 9, }; BEGIN { use Exporter 'import'; my @abc = qw{ABC_1 ABC_2 ABC_3}; my @def = qw{DEF_1 DEF_2 DEF_3}; my @ghi = qw{GHI_1 GHI_2 GHI_3}; my @abcdef = (@abc, @def); my @all = (@abc, @def, @ghi); our @EXPORT_OK = @all; our %EXPORT_TAGS = ( abc => [@abc], def => [@def], ghi => [@ghi], abcdef => [@abcdef], all => [@all], ); } 1;

And an alias, perl_sam_const, to facilitate testing:

$ alias perl_sam_const alias perl_sam_const='perl -I/home/ken/tmp/pm_11139384/lib -Mstrict -M +warnings -E'

Now I can:

# import a single constant $ perl_sam_const 'use Sam::Constants qw{ABC_2}; say ABC_2' 2 # check that other ABC_* constants are not imported $ perl_sam_const 'use Sam::Constants qw{ABC_2}; say for ABC_1, ABC_2, +ABC_3' Bareword "ABC_1" not allowed while "strict subs" in use at -e line 1. Bareword "ABC_3" not allowed while "strict subs" in use at -e line 1. Execution of -e aborted due to compilation errors. # import all ABC_* constants $ perl_sam_const 'use Sam::Constants qw{:abc}; say for ABC_1, ABC_2, A +BC_3' 1 2 3 # import all ABC_* and GHI_* constants (using two tags) $ perl_sam_const 'use Sam::Constants qw{:abc :ghi}; say for ABC_1, GHI +_2' 1 8 # import all ABC_* and DEF_* constants (using just one tag) $ perl_sam_const 'use Sam::Constants qw{:abcdef}; say for DEF_3, ABC_3 +' 6 3 # import all constants $ perl_sam_const 'use Sam::Constants qw{:all}; say for ABC_1, DEF_2, G +HI_3' 1 5 9

See Exporter for an explanation of what I've done here, as well as details of other ways for doing this and other options available.

— Ken

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-04-19 19:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found