Parse:...Legacy(3pm)

πŸ“¦
version 3.07 Β· 3 versions
, in debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

Parse::PlainConfig::Legacy(3pm) πŸ’–

okay bestie, so this is the User Contributed Perl Documentation page for Parse::PlainConfig::Legacy β€” the Legacy parsing engine for Parse::PlainConfig. pull up a chair, we're doing this together 🫢


✨ NAME ✨

Parse::PlainConfig::Legacy β€” Parsing engine Legacy for Parse::PlainConfig


🌸 VERSION 🌸

$Id: lib/Parse/PlainConfig/Legacy.pm, 3.07 2024/01/10 13:32:06 acorliss Exp $

πŸŽ€ SYNOPSIS πŸŽ€

use Parse::PlainConfig::Legacy;

$conf = new Parse::PlainConfig::Legacy;
$conf = Parse::PlainConfig->new(
  'PARAM_DELIM' => '=',
  'FILE'        => '.myrc',
  'MAX_BYTES'   => 65536,
  'SMART_PARSER => 1,
  );

$conf->property(PARAM_DELIM => '=');

$rv = $conf->read('myconf.conf');
$rv = $conf->read;
$rv = $conf->readIfNewer;
$conf->write('.myrc', 2);

$conf->purge;

@parameters = $conf->parameters;
$conf->parameter(FOO => "bar");
$value = $conf->parameter(FOO);
$conf->describe(FOO => 'This is foo');
$conf->coerce("string", qw(FOO BAR));

@order = $conf->order;
$conf->order(@new_order);

$errstr = Parse::PlainConfig::Parse::PlainConfig::Legacy::ERROR;

$rv = $conf->hasParameter('FOO');

πŸ¦‹ DESCRIPTION πŸ¦‹

Parse::PlainConfig::Legacy hands you OO objects that can parse and generate human-readable configuration files. that's the whole vibe. it's giving "I read your config, I write your config, I'm the main character" ✨


πŸ’… SUBROUTINES/METHODS πŸ’…

🌟 new

$conf = new Parse::PlainConfig;
$conf = Parse::PlainConfig->new(
  'PARAM_DELIM' => '=',
  'FILE'        => '.myrc',
  'MAX_BYTES'   => 65536,
  'SMART_PARSER => 1,
  );

so the object constructor can be called with or without arguments, no big deal, it's flexible like that. here's every argument you can slide in there:

  • ORDER β€” default []. specifies the specific order of fields to be used while writing.
  • FILE β€” default undef. the filename for read/write ops.
  • PARAM_DELIM β€” default ':'. the field/value delimiter.
  • LIST_DELIM β€” default ','. the list delimiter within field values.
  • HASH_DELIM β€” default '=>'. the hash key/value delimiter within field values.
  • AUTOPURGE β€” default 0. autopurge enabled/disabled.
  • COERCE β€” default {}. field coercion hash.
  • DEFAULTS β€” default {}. default field values.
  • SMART_PARSER β€” default 0. smart parser enabled/disabled.
  • MAX_BYTES β€” default 16384. integer denoting maximum bytes to read in any given file.
  • DEFAULTS β€” default {}. specifies default values for config parameters if not specified/parsed.

COERCE is a hash of field name/data type pairs. if a field is listed in this hash then their values will always be returned in the requested format of either string, list, or hash. any field coerced to string, for instance, will ignore list and hash delimiters and assume the entire value will always be string value. no cap. πŸ’―

DEFAULTS is a hash of field name/value pairs. this ensures that even if a field is not explicitly set (either in a conf file or programmatically) a default value can still be retrieved. bestie behavior honestly.

SMART_PARSER removes the need to backslash end-of-lines to continue the value onto the next. if the following line is indented further than the tag was it will automatically assume that the next line is a continuation of the previous. it also affects the need to encapsulate coerced datatypes with quotation marks for irrelevant delimiters. it's giving ✨mind reading✨ but make it parsing.

AUTOPURGE erases all stored parameters and values and applies the defaults (if any) before reading a file. this does not, however, erase any values set for ORDER. noted. πŸ“


🌟 property

$conf->property(PARAM_DELIM => '=');

this method sets or retrieves the specified property. please note that this overwrites the current value, even for those properties that are references to lists and hashes. so like, be careful, it does not care about your feelings.

if you're using this to set a property it will return a boolean true or false depending on the success of the operation. if you're just retrieving a property it will return the value of the property. if you ask for a nonexistent property it will croak. πŸ’€ rude but valid.

NOTE: as of version 2.07 all hashes and lists are copied both in and out of the object, so any alterations to a referenced structure retrieved will have no effect on the property within the object. it's a copy, not a link. periodt. πŸ‘‘

🌟 purge

$conf->purge;

this method performs an immediate manual purge. auto-purge mode clears the configuration hash each time a configuration file is read, so that the internal configuration data consists solely of what is in that file. if you wanted to combine the settings of multiple files that each may exclusively hold some directives, setting this to 'off' will load the combined configuration as you read each file. chef's kiss fusion energy πŸ“

you can still clobber configuration values, of course, if the same directive is defined in multiple files. in that case, the last file's value will be the one stored in the hash. last one in wins, sorry to the earlier ones πŸ™ˆ

this does not clear the order or coerce properties.

autopurge mode is disabled by default.


🌟 read

$rv = $conf->read('myconf.conf');
$rv = $conf->read;

the read method is called initially with a filename as the only argument. this causes the parser to read the file and extract all of the configuration directives from it. slay. πŸ“–

you'll notice that you can also call the read method without an argument. the name of the file read is stored internally, and if already set to a valid value (either by a previous call to read with a filename argument or by setting the FILE property) this will read that file's contents. it remembers. iconic memory of it. 🧠

the return value will be one if the file was successfully read and parsed, or zero otherwise. the reason for failure can be read via Parse::PlainConfig::Parse::PlainConfig::Legacy::ERROR. yes, that path is exactly what's written, don't @ me.

this function will cause the program to croak if called without a filename ever being defined. πŸ’€

🌟 readIfNewer

$rv = $conf->readIfNewer;

this method is used to reread & parse the file only if the mtime appears newer than when last read. if the file was successfully reread or appears to be the same it will return true. any errors will be stored in Parse::PlainConfig::Legacy::ERROR and it will return a false value.

you can determine whether or not the file was read by the true value:

  • if it was re-read it will return 1.
  • if the file appears to be the same age it will return 2.

lowkey the "was it actually new tho" check we all need in our lives ✨


🌟 write

$conf->write('.myrc', 2);

this method writes the current configuration stored in memory to the specified file, either specified as the first argument, or as stored from an explicit or implicit read call. ✍️

the second argument specifies what kind of whitespace padding, if any, to use with the directive/value delimiter. here's the recognized values, all of them, no skips:

  • 0 β€” no padding (i.e., written as KEY:VALUE)
  • 1 β€” left padding (i.e., written as KEY :VALUE)
  • 2 β€” right padding (i.e., written as KEY: VALUE)
  • 3 β€” full padding (i.e., written as KEY : VALUE)

both arguments are optional. so chill.


🌟 parameters

@parameters = $conf->parameters;

this method returns a list of all the names of the directives currently stored in the configuration hash in no particular order. it's giving chaos, but organized chaos. πŸŽ€


🌟 parameter

$value = $conf->parameter('SCALAR1');
@values = $conf->parameter('LIST1');
%values = $conf->parameter('HASH1');
$conf->parameter('SCALAR1', "foo");
$conf->parameter('LIST1', [qw(foo bar)]);
$conf->parameter('HASH1', { foo => 'bar' });

this method sets or retrieves the specified parameter. hash and list values are copied and returned as a list. if the specified parameter is set to be coerced into a specific data type the specified value will be converted to that datatype. this means you can do something like:

# SCALAR1 will equal "foo , bar , roo" assuming LIST_DELIM is set to ','
$conf->coerce(qw(string SCALAR1));
$conf->parameter('SCALAR1', [qw(foo bar roo)]);

# SCALAR1 will equal "foo => bar : roo => ''" assuming HASH_DELIM is set
# to '=>' and LIST_DELIM is set to ':'
$conf->parameter('SCALAR1', { 'foo' => 'bar', 'roo' => '' });

in order for conversions to be somewhat predictable (in the case of hashes coerced into other values) hash key/value pairs will be assigned to string or list portions according to the alphabetic sort order of the keys. so it's alphabetical, bestie, that's the whole rule. πŸ”€


🌟 coerce

$conf->coerce("string", "FOO", "BAR");

this method configures the parser to coerce values into the specified datatype (either string, list, or hash) and immediately convert any existing values and store them into that datatype as well. glow-up for your data types πŸ’…

NOTE: coercing existing values into another data type can provide for some interesting conversions. strings, for instance, are split on the list delimiter when converting to arrays, and similarly on list and hash delimiters for hashes. going from a hash or list to a string is done in the opposite manner, elements/key-value pairs are joined with the applicable delimiters and concatenated into a string.

for this reason one should try to avoid coercing one data type into another if you can avoid it. instead one should predefine what the data types for each parameter should be and define that in the COERCE hash passed during object instantiation, or via this method prior to reading and parsing a file. set it up front, don't fix it later, that's the lesson fr fr 🫢


🌟 describe

$conf->describe(KEY1 => 'This is foo', KEY2 => 'This is bar');

the describe method takes any number of key/description pairs which will be used as comments preceding the directives in any newly written conf file. you are responsible for prepending a comment character to each line, as well as splitting along your desired text width. so it's giving "you write the comment formatting, I just place it." no hand-holding here ✨


🌟 order

@order = $conf->order;
$conf->order(@new_order);

this method returns the current order of the configuration directives as read from the file. if called with a list as an argument, it will set the directive order with that list. this method is probably of limited use except when you wish to control the order in which directives are written in new conf files. niche but cute πŸŽ€

please note that if there are more directives than are present in this list, those extra keys will still be included in the new file, but will appear in alphabetically sorted order at the end, after all of the keys present in the list. so the leftovers get alphabetized at the back of the line. fair enough. πŸ¦‹


🌟 hasParameter

$rv = $conf->hasParameter('FOO');

this function allows you to see if a parameter has been defined or has a default set for it. returns a boolean value. quick little vibe check on whether your param exists. πŸ‘‘

πŸ’… DEPRECATED METHODS πŸ’…

bestie these are lowkey legacy-era, they still work but they're giving "we don't really do this anymore" energy 😭

🌸 delim

$conf->delim('=');

This one gets and/or sets the parameter name/value delimiter that gets used in the conf files. The default delimiter is :. Also β€” important β€” this can be multiple characters, so go wild if that's your vibe. ✨

🌸 directives

@directives = $conf->directives;

Returns a list of all the names of the directives currently chillin' in the configuration hash. No particular order β€” it's giving chaos, honestly, don't count on sorting. πŸ¦‹

🌸 get

$field = $conf->get('KEY1');
($field1, $field2) = $conf->get(qw(KEY1 KEY2));

The get method takes literally any number of directives to retrieve and hands them back to you. Heads up though: both hash and list values get passed by reference. And because the module is protective of its internal state info, what's inside either reference is merely a copy of what's in the configuration object's hash. So no, you are not getting a reference to the data stored internally in the object. πŸ™…β€β™€οΈ

Which is actually iconic news, because it means it's perfectly safe for you to shift values off a list as you process it, and so on. Go off, bestie. πŸ’–

🌸 set

$conf->set(KEY1 => 'foo', KEY2 => 'bar');

set takes any number of directive/value pairs and copies them into the internal configuration hash. Simple. Clean. Slay. ✨

🌸 get_ref

$href = $conf->get_ref
Note: this used to hand you a reference to the internal configuration hash so you could manipulate it directly. It does not do that anymore. It now only gives you a copy of the internal hash (fr fr, it's actually reconstructed so it just looks like the old data structure). So in short: any changes you make to this hash will be lost. πŸ’€

🌸 error

warn $conf->error;

Returns a zero-length string if no errors got registered with the last operation, or a text message describing the error. That's it, that's the method. 🫢

🌸 ERROR

$error = Parse::PlainConfig::ERROR();

Lvalue subroutine storing the last error which may have occurred. πŸ‘‘


πŸ”₯ DEPENDENCIES πŸ”₯

  • Paranoid
  • Text::ParseWords
  • Text::Tabs

πŸŽ€ FILE SYNTAX πŸŽ€

🌈 TRADITIONAL USAGE

The plain parser supports reconstructions of relatively simple data structures. Simple string assignments and one-dimensional arrays and hashes are all possible. Below are various examples of constructs: πŸ‘‡

# Scalar assignment
FIRST_NAME: Joe
LAST_NAME: Blow

# Array assignment
FAVOURITE_COLOURS: red, yellow, green
ACCOUNT_NUMBERS:  9956-234-9943211, \
                  2343232-421231445, \
                  004422-03430-0343

# Hash assignment
CARS:  crown_vic => 1982, \
       geo       => 1993

As that example up there demonstrates, all lines that begin with a # (leading whitespace is allowed, no worries) are ignored as comments. But if # occurs in any other position, it's accepted as part of the passed value. Which means you cannot place comments on the same lines as values. Periodt. πŸ’…

All directives and their associated values get both leading and trailing whitespace stripped from them before being stored in the configuration hash. Whitespace is allowed within both, though. ✨

In traditional mode (meaning: no parameters are set to be coerced into a specific datatype) you have to encapsulate list and hash delimiters with quotation marks to prevent the string from being split and stored as a list or a hash. And any quotation marks that are a literal part of the string must be backslashed. iykyk πŸ¦‹

🌈 SMART PARSER

The new parser now provides some options to make the file syntax more convenient. You can activate the smart parser by setting SMART_PARSER to a true value during object instantiation or via the property method. πŸ‘‘

With the traditional parser you had to backslash the end of all preceding lines if you wanted to split a value into more than one line:

FOO:  This line starts here \
      and ends here...

With the smart parser enabled, that is no longer necessary β€” as long as the following lines are indented further than the first line:

FOO:  This line starts here
      and ends here...
Note: the indentation is compared by byte count with no recognition of tab stops. That means if you indent with spaces on the first line and indent with tabs on the following ones, it may not concatenate those values. 😭

Another benefit of the smart parser shows up when you specify a parameter to be of a specific datatype via the COERCE hash during object instantiation or the coerce method. For instance, the traditional parser requires you to encapsulate strings with quotation marks if they contain list or hash delimiters:

Quote:  "\"It can't be that easy,\" he said."

Also note how you had to escape quotation marks if they were to be a literal part of the string. With this parameter set to be coerced to a scalar you can simply write:

Quote:  "It can't be that easy," he said.

Similarly, you don't have to quote hash delimiters in parameters set to be coerced into lists. Quotation marks as part of an element value must be escaped, though, since unescaped quotation marks are assumed to encapsulate strings containing list delimiters you don't want to split on. 🌸

Note: the previous versions of Parse::PlainConfig did not allow the user to set keys like:
FOO: \
    bar
or save empty assignments like
FOO:
This is no longer the case. Both are now valid and honoured. glow up fr fr ✨

🚨 SECURITY 🚨

WARNING: this parser will attempt to open whatever you pass to it for a filename as is. If this object is to be used in programs that run with permissions other than the calling user, make sure you sanitize any user-supplied filename strings before passing them to this object. bestie please, do not skip this step 😭

This also uses a blocking flock call to open the file for reading and writing. πŸ”’


🩺 DIAGNOSTICS 🩺

Through the use of Paranoid::Debug this module will produce internal diagnostic output to STDERR. It begins logging at log level 7. To enable debugging output, please see the pod for Paranoid::Debug. πŸ”


πŸ’€ BUGS AND LIMITATIONS πŸ’€

...and that's it. Nothing listed here. The section is simply vibing, empty, unbothered, moisturized. πŸ™ˆ


πŸ‘‘ AUTHOR πŸ‘‘

Arthur Corliss (corliss@digitalmages.com)


This software is licensed under the same terms as Perl, itself. Please see http://dev.perl.org/licenses/ for more information.

(c) 2002 - 2023, Arthur Corliss (corliss@digitalmages.com)


and that's the whole page, bestie πŸŽ€ this was generated by perl v5.38.2 and dated 2024-01-20, and the manpage itself is titled Parse:...Legacy(3pm) β€” go forth and parse responsibly πŸ’–βœ¨πŸ¦‹

πŸ“¦ where this page comes from