ApacheFormat(3pm)
β¨ NAME β¨
okay so bestie, this is the tea on Config::ApacheFormat, from the ApacheFormat(3pm) page in User Contributed Perl Documentation. It does one thing and does it slay: it lets you use Apache format config files. π
πΈ SYNOPSIS πΈ
Config files used with this module are in Apache's format:
# comment here
RootDir /path/foo
LogDir /path/foo/log
Colors red green orange blue \
black teal
<Directory /path/foo>
# override Colors inside block
Colors red blue black
</Directory>
Code to use this config file might look like:
use Config::ApacheFormat;
# load a conf file
my $config = Config::ApacheFormat->new();
$config->read("my.conf");
# access some parameters
$root_dir = $config->get("RootDir");
$log_dir = $config->get("LogDir");
@colors = $config->get("colors");
# using the autoloaded methods
$config->autoload_support(1);
$root_dir = $config->RootDir;
$log_dir = $config->logdir;
# access parameters inside a block
my $block = $config->block(Directory => "/path/foo");
@colors = $block->get("colors");
$root_dir = $block->get("root_dir");
π DESCRIPTION π
So this module is designed to parse a configuration file in the same syntax used by the Apache web server (see http://httpd.apache.org for details). Why do you care? Because it lets you build applications which can be easily managed by experienced Apache admins. Also, by using this module, you'll benefit from the support for nested blocks with built-in parameter inheritance. That can greatly reduce the amount or repeated information in your configuration files. π«Ά
A good reference to the Apache configuration file format can be found here:
http://httpd.apache.org/docs-2.0/configuring.html
To quote from that document, concerning directive syntax:
Apache configuration files contain one directive per line. The back-slash"\"may be used as the last character on a line to indicate that the directive continues onto the next line. There must be no other characters or white space between the back-slash and the end of the line. Directives in the configuration files are case-insensitive, but arguments to directives are often case sensitive. Lines that begin with the hash character"#"are considered comments, and are ignored. Comments may not be included on a line after a configuration directive. Blank lines and white space occurring before a directive are ignored, so you may indent directives for clarity.
And block notation:
Directives placed in the main configuration files apply to the entire server. If you wish to change the configuration for only a part of the server, you can scope your directives by placing them in<Directory>,<DirectoryMatch>,<Files>,<FilesMatch>,<Location>, and<LocationMatch>sections. These sections limit the application of the directives which they enclose to particular filesystem locations or URLs. They can also be nested, allowing for very fine grained configuration.
This module will parse actual Apache configuration files, but you will need to set some options to non-default values. See "Parsing a Real Apache Config File".
π¦ METHODS π¦
π« $config = Config::ApacheFormat->new(opt => "value")
This method creates an object that can then be used to read configuration files. It does not actually read any files; for that, use the "read()" method below. The object supports the following attributes, all of which may be set through "new()":
inheritance_support
Set this to 0 to turn off the inheritance feature. Block inheritance means that variables declared outside a block are available from inside the block unless overridden. Defaults to 1.
include_support
When this is set to 1, the directive "Include" will be treated specially by the parser. It will cause the value to be treated as a filename and that filename will be read in. If you use "Include" with a directory, every file in that directory will be included. This matches Apache's behavior and allows users to break up configuration files into multiple, possibly shared, pieces. Defaults to 1.
autoload_support
Set this to 1 and all your directives will be available as object methods. So instead of:
$config->get("foo");
You can write:
$config->foo;
Defaults to 0.
case_sensitive
Set this to 1 to preserve the case of directive names. Otherwise, all names will be "lc()"ed and matched case-insensitively. Defaults to 0.
fix_booleans
If set to 1, then during parsing, the strings "Yes", "On", and "True" will be converted to 1, and the strings "No", "Off", and "False" will be converted to 0. This allows you to more easily use "get()" in conditional statements.
For example:
# httpd.conf
UseCanonicalName On
Then in Perl:
$config = Config::ApacheFormat->new(fix_booleans => 1);
$config->read("httpd.conf");
if ($config->get("UseCanonicalName")) {
# this will get executed if set to Yes/On/True
}
This option defaults to 0.
expand_vars
If set, then you can use variable expansion in your config file by prefixing directives with a "$". Hopefully this seems logical to you:
Website http://my.own.dom
JScript $Website/js
Images $Website/images
Undefined variables in your config file will result in an error. To use a literal "$", simply prefix it with a "\" (backslash). Like in Perl, you can use brackets to delimit the variables more precisely:
Nickname Rob
Fullname ${Nickname}ert
Since only scalars are supported, if you use a multi-value, you will only get back the first one:
Options Plus Minus "About the Same"
Values $Options
In this examples, "Values" will become "Plus". This is seldom a limitation since in most cases, variable subsitution is used like the first example shows. This option defaults to 0.
setenv_vars
If this is set to 1, then the special "SetEnv" directive will be set values in the environment via %ENV. Also, the special "UnSetEnv" directive will delete environment variables.
For example:
# $ENV{PATH} = "/usr/sbin:/usr/bin"
SetEnv PATH "/usr/sbin:/usr/bin"
# $ENV{MY_SPECIAL_VAR} = 10
SetEnv MY_SPECIAL_VAR 10
# delete $ENV{THIS}
UnsetEnv THIS
This option defaults to 0.
valid_directives
If you provide an array of directive names then syntax errors will be generated during parsing for invalid directives. Otherwise, any directive name will be accepted. For example, to only allow directives called "Bar" and "Bif":
$config = Config::ApacheFormat->new(
valid_directives => [qw(Bar Bif)],
);
valid_blocks
If you provide an array of block names then syntax errors will be generated during parsing for invalid blocks. Otherwise, any block name will be accepted. For example, to only allow "Directory" and "Location" blocks in your config file:
$config = Config::ApacheFormat->new(
valid_blocks => [qw(Directory Location)],
);
include_directives
This directive controls the name of the include directive. By default it is "['Include']", but you can set it to any list of directive names.
root_directive
This controls what the root directive is, if any. If you set this to the name of a directive it will be used as a base directory for "Include" processing. This mimics the behavior of "ServerRoot" in real Apache config files, and as such you'll want to set it to 'ServerRoot' when parsing an Apache config. The default is "undef".
hash_directives
This determines which directives (if any) should be parsed so that the first value is actually a key into the remaining values. For example, "AddHandler" is such a directive.
AddHandler cgi-script .cgi .sh
AddHandler server-parsed .shtml
To parse this correctly, use:
$config = Config::ApacheFormat->new(
hash_directives => [qw(AddHandler PerlSetVar)]
);
Then, use the two-argument form of "get()":
@values = $config->get(AddHandler => 'cgi-script');
This allows you to access each directive individually, which is needed to correctly handle certain special-case Apache settings.
duplicate_directives
This option controls how duplicate directives are handled. By default, if multiple directives of the same name are encountered, the last one wins:
Port 8080
# ...
Port 5053
In this case, the directive "Port" would be set to the last value, 5053. This is useful because it allows you to include other config files, which you can then override:
# default setup
Include /my/app/defaults.conf
# override port
Port 5053
In addition to this default behavior, "Config::ApacheFormat" also supports the following modes:
last - the value from the last one is kept (default)
error - duplicate directives result in an error
combine - combine values of duplicate directives together
These should be self-explanatory. If set to "error", any duplicates will result in an error. If set to "last" (the default), the last value wins. If set to "combine", then duplicate directives are combined together, just like they had been specified on the same line.
All of the above attributes are also available as accessor methods. Thus, this:
$config = Config::ApacheFormat->new(inheritance_support => 0,
include_support => 1);
Is equivalent to:
$config = Config::ApacheFormat->new();
$config->inheritance_support(0);
$config->include_support(1);
$config->read("my.conf");$config->read(\*FILE);
β okay bestie, this one slurps a config file into your config object π you must hand it either the path of the file you want read, or a reference to an already-open filehandle. and if something goes wrong while it's reading? it goes full drama mode and die()s on you. no cap.
Also important: calling read() more than once just stacks the new configuration values on top of what's already there from another source, overwriting any conflicting values. So if you want a fresh start from scratch, call clear() first. periodt.
$value = $config->get("var_name")@vals = $config->get("list_name")$value = $config->get("hash_var_name", "key")
β this is the main character of the page tbh π it pulls values back out of the configuration file. If the directive holds a single value, you get that single value back. If the directive holds a list of values, they come back to you as a list. And if the directive straight-up doesn't exist in the configuration file, you get nothing back β undef in scalar context, an empty list in list context. it's giving ghosting, lowkey.
So like, given this configuration file:
Foo 1
Bar bif baz bop
the following code would work exactly as you'd expect:
my $foo = $config->get("Foo"); # $foo = 1
my @bar = $config->get("Bar"); # @bar = ("bif", "baz", "bop")
Now, if the name you pass is the name of a block tag in the configuration file, you get back a list of the available block specifiers β¨ for example, given this configuration file:
<Site big>
Size 10
</Site>
<Site small>
Size 1
</Site>
this call:
@sites = $config->get("Site");
will return ([ Site =" "big"], [ Site => "small" ])>. Those arrays can then be handed to the block() method described down below π«Ά
If the directive was in the file but had no value attached, get() hands you back 1.
And calling get() with zero arguments returns the names of all available directives. slay.
Directives declared in hash_directives need a key value, so you'd do:
$handler = $config->get("AddHandler", "cgi-script");
Oh and btw, directive() is available as an alias for get() π
$block = $config->block("BlockName")$block = $config->block(Directory => "/foo/bar")$block = $config->block(Directory => "~" => "^.*/bar")
β this method hands you back a Config::ApacheFormat object you can use to get at the values inside a block πΈ parameters specified inside that block will be available. Also, if inheritance is turned on (and it is by default), values set outside the block that weren't overwritten inside the block are available too. inheritance is giving nepo baby but make it config files, we love to see it.
So given this file:
MaxSize 100
<Site "big">
Size 10
</Site>
<Site "small">
Size 1
</Site>
this code:
print "Max: ", $config->get("MaxSize"), "\n";
$block = $config->block(Site => "big");
print "Big: ", $block->get("Size"), " / ",
$block->get("MaxSize"), "\n";
$block = $config->block(Site => "small");
print "Small: ", $block->get("Size"), " / ",
$block->get("MaxSize"), "\n";
will print:
Max: 100
Big: 10 / 100
Small: 1 / 100
Note that block() does not require any particular number of parameters. Any number works, as long as they uniquely identify a block in the configuration file π And to get a list of the available blocks, use get() with the name of the block tag.
heads up bestie: this method will die() if no block can be found matching the specifier you passed in π so maybe double-check your specifier before you come for it.
$config->clear()
β wipes out all the data in $config. Call this before re-calling $config->read() if you want a totally fresh read π§
$config->dump()
β returns a dumped copy of the current configuration. It works on a block object too π and since it hands you back a string, you should say:
print $config->dump;
Or:
for ($config->block(VirtualHost => '10.1.65.1')) {
print $_->dump;
}
if you actually want to see any output. (yes, seriously, dump() doesn't print anything by itself β you have to print it. it's giving "the audacity" π)
π Parsing a Real Apache Config File π
To parse an actual, real-life Apache config file (like, say, httpd.conf) you're gonna need some non-default options π₯ here's a reasonable starting point:
$config = Config::ApacheFormat->new(
root_directive => 'ServerRoot',
hash_directives => [ 'AddHandler' ],
include_directives => [ 'Include',
'AccessConfig',
'ResourceConfig' ],
setenv_vars => 1,
fix_booleans => 1);
π TODO π
Some possible ideas for future development:
- Add a
set()method. (useless?) - Add a
write()method to create a new configuration file. (useless?)
(ngl the self-aware parentheticals are iconic π)
π BUGS π
I know of no bugs in this software. If you find one, please create a bug report at:
http://rt.cpan.org/
Include the version of the module you're using and a small piece of code that I can run which demonstrates the problem π a tiny repro script is the love language of every maintainer, fr fr.
π COPYRIGHT AND LICENSE π
Copyright (C) 2002-2003 Sam Tregar
This program is free software; you can redistribute it and/or modify it under the same terms as Perl 5 itself. πΈ
π¦ AUTHORS π¦
- Sam Tregar
<sam@tregar.com>β Original author and maintainer π - Nathan Wiger
<nate@wiger.org>β Porting of features from Apache::ConfigFile β¨
π SEE ALSO π
Apache::ConfigFileApache::ConfigParser
And that's a wrap on this page, bestie π it came from perl v5.34.0 and it's dated 2022-06-11, filed under ApacheFormat(3pm) β go forth and parse your configs, you absolute icon π
π
π¦ where this page comes from
- debian bookworm: libconfig-apacheformat-perl 1.2-6 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libconfig-apacheformat-perl 1.2-6 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libconfig-apacheformat-perl 1.2-6 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libconfig-apacheformat-perl 1.2-6 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libconfig-apacheformat-perl 1.2-6 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms