in reply to Deferring variables
G'day Chuma,
I'd define your parameters and default values in a separate file. For this example, I've used JSON:
$ cat pm_11145036_parm_defaults.json { "margin-left" : [ null, "margin-horizontal" ], "margin-right" : [ null, "margin-horizontal" ], "margin-top" : [ null, "margin-vertical" ], "margin-bottom" : [ null, "margin-vertical" ], "margin-horizontal" : [ null, "margin" ], "margin-vertical" : [ null, "margin" ], "margin" : [ 10, null ] }
The following code is a rough example of how that might be used.
#!/usr/bin/env perl use strict; use warnings; use autodie; use constant { VALUE => 0, DEFER => 1, }; use JSON; my $json_file = 'pm_11145036_parm_defaults.json'; my $par = decode_json( do { local $/; open my $fh, '<', $json_file; <$fh>; } ); sub _get { my ($key) = @_; if (! defined $par->{$key}[VALUE]) { _get($par->{$key}[DEFER]) } else { return $par->{$key}[VALUE]; } } sub _set { my ($key, $value) = @_; if (! defined $par->{$key}[DEFER]) { warn "Can't change factory default: '$key'.\n"; } else { $par->{$key}[VALUE] = $value; } return; } # Some examples of usage: print 'margin-left = ', _get('margin-left'), "\n"; _set('margin-horizontal', 20); print 'margin-left = ', _get('margin-left'), "\n"; _set('margin-left', 30); print 'margin-left = ', _get('margin-left'), "\n"; print 'margin = ', _get('margin'), "\n"; _set('margin', 50); print 'margin = ', _get('margin'), "\n";
Output:
margin-left = 10 margin-left = 20 margin-left = 30 margin = 10 Can't change factory default: 'margin'. margin = 10
Notes:
- Keeping your data separate means it can reused in all of your programs: no need to tweak %par in multiple scripts (potentially a lot of work; certainly error-prone).
- When a user has set preferences, these can be stored in a separate file for reuse across all programs; e.g. parm_USERNAME.json.
- For further reuse, put most of that code in a module; then each program just needs something like use Chuma::Layouts;.
- I only used JSON as an example. It's not intended as a recommendation: pick whatever you want.
— Ken
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Deferring variables
by perlfan (Vicar) on Jul 04, 2022 at 13:54 UTC |
In Section
Seekers of Perl Wisdom