Config...mputer(3pm)

๐Ÿ’ป Config::Model::ValueComputer โ€” the manual page, but make it cute โœจ

okay bestie, so this is Config::Model::ValueComputer(3pm), from the User Contributed Perl Documentation corner of the world. It's version 2.166, and it's literally the class that does the mathโœจ for your config values. Think: your config tree has entries, and this thing goes "oh you want a value? I gotchu, I'll compute it from some other values with a formula". It's giving calculator but make it fashion ๐ŸŽ€


๐ŸŒˆ SYNOPSIS

okay so here's the whole vibe in code, no notes:

use Config::Model;

# define configuration tree object
my $model = Config::Model->new;
$model ->create_config_class (
   name => "MyClass",

   element => [
      av => {
          type => 'leaf',
          value_type => 'integer',
      },
      bv => '*av',
      compute_int => {
              type => 'leaf',
              value_type => 'integer',
              compute    => {
                  formula   => '$a + $b',
                  variables => { a => '- av', b => '- bv'}
              },
      },
   ],
);

my $inst = $model->instance(root_class_name => 'MyClass' );

my $root = $inst->config_root ;

# put data
$root->load( steps => 'av=33 bv=9' );

print "Computed value is ",$root->grab_value('compute_int'),"\n";
# Computed value is 42

and yes the answer is 42 because 33 + 9 and because the universe said so ๐Ÿฆ‹


๐Ÿ’– DESCRIPTION

So basically this class gives you a way to compute a configuration value. The computation uses a formula plus some other configuration values that live in the configuration tree. It's like, the config tree is a group chat and this value is the one who's like "besties I'm deriving my whole personality from y'all" ๐Ÿ’…

And here's the cute part: the computed value can be overridden. In other words, the computed value can be used as a default value. So it's a LARP, it's a suggestion, it's a placeholder that slays ๐Ÿ”ฅ

๐Ÿงฎ Computed value declaration

A computed value has to be declared in a 'leaf' element. That leaf element needs a "compute" argument that points to a hash ref.

That array ref contains:

  • A string formula that use variables and replace function.
  • A set of variable and their relative location in the tree (using the notation explained in grab method
  • An optional set of replace rules.
  • An optional parameter to force a Perl eval of a string.
โš ๏ธ heads up, bestie: a variable must point to a valid location in the configuration tree โ€” even when &index() or "$replace{}" is being used. After substitution of these functions, the string is used as a path (See grab) starting from the computed value. So the path has to begin with "!" to go back to root node, or "-" to go up a level. No wandering off into the void, okay? ๐Ÿ•ณ๏ธ

โœจ Compute formula

The first element of the "compute" array ref must be a string that contains the computation algorithm โ€” like, a formula for arithmetic computation for integer values, or a string template for string values.

This string or formula should contain variables (like $foo or $bar). And quick note, because this trips people up: these variables are not interpolated by Perl ๐Ÿ˜ค

For instance:

'My cat has $nb legs'
'$m * $c**2'

This string or formula may also contain:

  • The index value of the current object : &index or &index().
  • The index value of a parent object: &index(-). Ancestor index value can be retrieved with &index(-2) or &index(-3) or "&index(- -)" or "&index(- - -)"
  • The element name of the current object: &element or &element().
  • The element name of a parent object: &element(-). Likewise, ancestor element name can be retrieved with &element(-2) or &element(-3).
  • The full location (path) of the current object: &location or &location().

For instance, you could have this template string:

'my element is &element, my index is &index' .
 'upper element is &element(-), upper index is &index(-)',

So if you need to perform more complex operations than substitution โ€” like extraction with regular expressions โ€” you can force an eval done by Perl with "use_eval => 1". In this case, the result of the eval is used as the computed value. Living dangerously, love that for you ๐Ÿ’€

For instance:

# extract host from url
compute => {
    formula => '$old =~ m!http://[\w\.]+(?::\d+)?(/.*)!; $1 ;',
    variables => { old => '- url' } ,
        use_eval => 1 ,
},

# capitalize
compute => {
    formula => 'uc($old)',
        variables => { old => '- small_caps' } ,
        use_eval => 1
}

๐Ÿ”ค Compute variables

Compute variables are a set of "key => value" pairs that define the variables used in the specified formula. The key is a variable name used in the string that represents the formula. The value is a string that is used to get the correct Value object. It's basically a lil phonebook: key goes in, the right Value object comes out ๐Ÿ“–

In this numeric example, "result" default value is "av + bv":

element => [
   av => {
       type => 'leaf',
       value_type => 'integer'
   },
   bv => {
       type => 'leaf',
       value_type => 'integer'
   },
   result => {
       type => 'leaf',
       value_type => 'integer',
       compute => {
           formula => '$a + $b' ,
           variables => { a => '- av', b => '- bv' },
       }
   }
]

In this string example, the default value of the "Comp" element is actually a string made of ""macro is "" and the value of the ""macro"" element of the object located 2 nodes above:

comp => {
   type => 'leaf',
   value_type => 'string',
   compute => {
       formula => '"macro is $m"' ,
       variables => { m => '- - macro' }
   }
}

๐ŸŽ€ Compute replace

Sometime, using the value of a tree leaf is not enough and you need to substitute a replacement for any value you can get. This replacement can be done using a hash like notation within the formula using the %replace hash. It's the glow-up pass, the "let me translate that for the girls" step ๐Ÿ’…

For instance, if you want to display a summary of a config, you can do :

compute_with_replace => {
    formula => '$replace{$who} is the $replace{$what} of $replace{$country}',
    variables => {
        who   => '! who' ,
        what  => '! what' ,
        country => '- country',
    },
    replace => {
        chief => 'president',
        America => 'USA'
    }
}

๐ŸŒ€ Complex formula

&index, &element, and replace can be combined. But the argument of &element or &index can only be a value object specification (I.e. something like '"- - foo"'), it cannot be a value replacement of another &element or &index.

I.e. &element($foo) is ok, but "&element(&index($foo))" is not allowed. โœ‹ like, know your limits bestie.

๐Ÿช† computed variable

Compute variables can themselves be computed :

compute => {
   formula => 'get_element is $replace{$s}, indirect value is \'$v\'',
   variables => {
       s => '! $where',
       where => '! where_is_element',
       v => '! $replace{$s}',
   }
   replace => {
       m_value_element => 'm_value',
       compute_element => 'compute'
   }
}
โš ๏ธ Be sure not to specify a loop when doing recursive computation. Rookie mistake, do not do it, the whole thing will just keep going like a group chat that never ends ๐Ÿ˜ญ

The function &index &element and &location are also allowed.

๐Ÿซถ compute override

In some case, a computed value must be interpreted as a default value and the user must be able to override this computed default value. In this case, you must use "allow_override => 1" with the compute parameter:

computed_value_with_override => {
   type => 'leaf',
   value_type => 'string',
   compute => {
       formula => '"macro is $m"' ,
       variables => { m => '- - macro' } ,
       allow_override => 1,
   }
}

This computed default value is written to the configuration file. Yeah, it gets saved. It's permanent now, it's on the record ๐Ÿ“

This default value may be already known by the application so the computed value should not be written to the configuration file. The computed value is interesting because it can be shown to the user. In this case, use the "use_as_upstream_default" parameter:

compute_known_upstream => {
   type => 'leaf',
   value_type => 'string',
   compute => {
       formula => '"macro is $m"' ,
       variables => { m => '- - macro' } ,
       use_as_upstream_default => 1,
   }
}

"use_as_upstream_default" implies "allow_override". so that's automatic, no cap ๐Ÿ‘‘

๐ŸŒซ๏ธ Undefined variables

You may need to compute value where one of the variables (i.e. other configuration parameter) is undefined. By default, any formula yields an undefined value if one variable is undefined. That's just the rules ๐Ÿ˜”

You may change this behavior with "undef_is" parameter. With this parameter, you can specify a "fallback" value that is used in your formula instead of an undefined variable. A lil safety net, we love to see it ๐Ÿฅบ

The most useful fallback values are:

undef_is => "''", # for string values
undef_is => 0   , # for integers, boolean values

Example:

Source => {
   type => 'leaf',
   value_type   => 'string',
   mandatory    => 1,
   migrate_from => {
       use_eval  => 1,
       formula   => '$old || $older ;',
       undef_is => "''",
       variables => {
           older => '- Original-Source-Location',
           old   => '- Upstream-Source'
       }
   },
},
[qw/Upstream-Source Original-Source-Location/] => {
   value_type => 'string',
   status     => 'deprecated',
   type       => 'leaf'
}

and that's where part 1 leaves us bestie, the rest is coming โœจ don't go anywhere ๐Ÿ’–

๐ŸŽ€ Examples ๐ŸŽ€

okay bestie, now for the part everyone actually scrolls to: real live examples โœจ watch how a computed value looks when it's actually sitting in a model, no cap.

๐Ÿ’– String substitution ๐Ÿ’–

sav => {
    type       => 'leaf',
    value_type => 'string',
  },
sbv => '*sav',
compute_string => {
    type       => 'leaf',
    value_type => 'string',
    compute    => {
        formula   => 'meet $a and $b',
        variables => { '- sav', b => '- sbv' }
    },
},

so sav is just a plain little leaf with type => 'leaf' and value_type => 'string', and sbv is chillin' as '*sav', pointing straight at it ๐Ÿ‘€. then compute_string rolls up as another 'leaf' / 'string' situation, except it's got a compute block: the formula is meet $a and $b, and variables carries - sav plus b => '- sbv'. that's the whole vibe. iconic, honestly ๐Ÿซถ

๐ŸŒธ Computation with on-the-fly replacement ๐ŸŒธ

compute_with_replace => {
    type       => 'leaf',
    value_type => 'string',
    compute    => {
        formula =>
          '$replace{$who} is the $replace{$what} of $replace{$country}',
        variables => {
            who     => '! who',
            what    => '! what',
            country => '- country',
        },
        replace => {
            chief   => 'president',
            America => 'USA'
        },
    },
  },

the way this works is so cute: the formula is '$replace{$who} is the $replace{$what} of $replace{$country}', so it's dipping into a replace hash and using other variables as the keys ๐Ÿ’…. who grabs ! who, what grabs ! what, and country grabs - country. then replace itself is handing over chief => 'president' and America => 'USA'. on-the-fly replacement, exactly like the section title said. periodt ๐Ÿฆ‹

๐Ÿฆ‹ Extract data from a value using a Perl regexp ๐Ÿฆ‹

Extract the host name from an URL:

url => {
    type       => 'leaf',
    value_type => 'uniline'
},
extract_host_from_url => {
    type       => 'leaf',
    value_type => 'uniline',
    compute    => {
        formula   => '$old =~ m!http://([\w\.]+)!; $1 ;',
        variables => { old => '- url' },
        use_eval  => 1,
    },
},

peep the formula: '$old =~ m!http://([\w\.]+)!; $1 ;' โ€” it runs that match against $old, which is wired up as - url, and then hands you back $1 ๐Ÿ˜Œ. and yes, use_eval => 1 is right there in the mix, because this one is โœจevaluatingโœจ its way to your answer. gorgeous.

๐ŸŒˆ copy hash example ๐ŸŒˆ

copying a hash may not be useful, but using &index() in a variable can be ๐Ÿ‘€

Here's an example where the hashes contain leaves.

The model is set up so that the content of copy_from is copied into the copy_to hash:

copy_from => {
    'type' => 'hash',
    'index_type' => 'string',
    'cargo' => {
        'config_class_name' => 'From',
        'type' => 'node'
    },
},
copy_to => {
    'type' => 'hash',
    'index_type' => 'string',
    'cargo' => {
        'type' => 'leaf',
        'value_type' => 'uniline',
        'compute' => {
            'formula' => '$copied',
            'variables' => {
                'copied' => '- copy_from:&index()'
            }
        },
    },
},

hash copy is also possible when the hash contains node ๐Ÿ’€ here's an example where the data to be copied is stored within a node. the main class has 2 hash elements:

copy_from => {
    'type' => 'hash',
    'index_type' => 'string',
    'cargo' => {
        'config_class_name' => 'From',
        'type' => 'node'
    },
},
copy_to => {
    'type' => 'hash',
    'index_type' => 'string',
    'cargo' => {
        'config_class_name' => 'To',
        'type' => 'node'
    },
},

the class we're copying from is quite short:

'name' => 'From',
'element' => [
    name =>  {
        'type' => 'leaf',
        'value_type' => 'uniline',
    }
]

and here's the class we're copying to:

'name' => 'To',
'element' => [
    name =>  {
        'type' => 'leaf',
        'value_type' => 'uniline',
        'compute' => {
            'formula' => '$copied',
            'variables' => {
                'copied' => '! copy_from:&index(-) name'
            }
        },
    }
]

๐Ÿ‘‘ AUTHOR ๐Ÿ‘‘

Dominique Dumont, (ddumont at cpan dot org)

๐Ÿ”ฅ SEE ALSO ๐Ÿ”ฅ

  • Config::Model
  • Config::Model::Instance
  • Config::Model::Value

๐Ÿ’œ AUTHOR ๐Ÿ’œ

Dominique Dumont

This software is Copyright (c) 2005-2022 by Dominique Dumont.

This is free software, licensed under:

  The GNU Lesser General Public License, Version 2.1, February 1999

and that's a wrap bestie ๐Ÿ’– this whole thing came to you via perl v5.42.3, dated 2026-07-23 ๐ŸŽ€ go forth and compute, you absolute main character ๐ŸŒŸ

๐Ÿ“ฆ where this page comes from