Config::Tiny - Read/Write .ini style files with as little code as possible


Config-Tiny documentation Contained in the Config-Tiny distribution.

Index


Code Index:

NAME

Top

Config::Tiny - Read/Write .ini style files with as little code as possible

SYNOPSIS

Top

    # In your configuration file
    rootproperty=blah

    [section]
    one=twp
    three= four
    Foo =Bar
    empty=

    # In your program
    use Config::Tiny;

    # Create a config
    my $Config = Config::Tiny->new;

    # Open the config
    $Config = Config::Tiny->read( 'file.conf' );

    # Reading properties
    my $rootproperty = $Config->{_}->{rootproperty};
    my $one = $Config->{section}->{one};
    my $Foo = $Config->{section}->{Foo};

    # Changing data
    $Config->{newsection} = { this => 'that' }; # Add a section
    $Config->{section}->{Foo} = 'Not Bar!';     # Change a value
    delete $Config->{_};                        # Delete a value or section

    # Save a config
    $Config->write( 'file.conf' );

DESCRIPTION

Top

Config::Tiny is a perl class to read and write .ini style configuration files with as little code as possible, reducing load time and memory overhead. Most of the time it is accepted that Perl applications use a lot of memory and modules. The ::Tiny family of modules is specifically intended to provide an ultralight alternative to the standard modules.

This module is primarily for reading human written files, and anything we write shouldn't need to have documentation/comments. If you need something with more power move up to Config::Simple, Config::General or one of the many other Config:: modules. To rephrase, Config::Tiny does not preserve your comments, whitespace, or the order of your config file.

CONFIGURATION FILE SYNTAX

Top

Files are the same format as for windows .ini files. For example:

	[section]
	var1=value1
	var2=value2

If a property is outside of a section at the beginning of a file, it will be assigned to the "root section", available at $Config->{_}.

Lines starting with '#' or ';' are considered comments and ignored, as are blank lines.

When writing back to the config file, all comments, custom whitespace, and the ordering of your config file elements is discarded. If you need to keep the human elements of a config when writing back, upgrade to something better, this module is not for you.

METHODS

Top

new

The constructor new creates and returns an empty Config::Tiny object.

read $filename

The read constructor reads a config file, and returns a new Config::Tiny object containing the properties in the file.

Returns the object on success, or undef on error.

When read fails, Config::Tiny sets an error message internally you can recover via Config::Tiny->errstr. Although in some cases a failed read will also set the operating system error variable $!, not all errors do and you should not rely on using the $! variable.

read_string $string;

The read_string method takes as argument the contents of a config file as a string and returns the Config::Tiny object for it.

write $filename

The write method generates the file content for the properties, and writes it to disk to the filename specified.

Returns true on success or undef on error.

write_string

Generates the file content for the object and returns it as a string.

errstr

When an error occurs, you can retrieve the error message either from the $Config::Tiny::errstr variable, or using the errstr() method.

CAVEATS

Top

Unsupported Section Headers

Some edge cases in section headers are not support, and additionally may not be detected when writing the config file.

Specifically, section headers with leading whitespace, trailing whitespace, or newlines anywhere in the section header, will not be written correctly to the file and may cause file corruption.

SUPPORT

Top

Bugs should be reported via the CPAN bug tracker at

http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Config-Tiny

For other issues, or commercial enhancement or support, contact the author.

AUTHOR

Top

Adam Kennedy <adamk@cpan.org>

ACKNOWLEGEMENTS

Top

Thanks to Sherzod Ruzmetov <sherzodr@cpan.org> for Config::Simple, which inspired this module by being not quite "simple" enough for me :)

SEE ALSO

Top

Config::Simple, Config::General, ali.as

COPYRIGHT

Top


Config-Tiny documentation Contained in the Config-Tiny distribution.

package Config::Tiny;

# If you thought Config::Simple was small...

use strict;
BEGIN {
	require 5.004;
	$Config::Tiny::VERSION = '2.14';
	$Config::Tiny::errstr  = '';
}

# Create an empty object
sub new { bless {}, shift }

# Create an object from a file
sub read {
	my $class = ref $_[0] ? ref shift : shift;

	# Check the file
	my $file = shift or return $class->_error( 'You did not specify a file name' );
	return $class->_error( "File '$file' does not exist" )              unless -e $file;
	return $class->_error( "'$file' is a directory, not a file" )       unless -f _;
	return $class->_error( "Insufficient permissions to read '$file'" ) unless -r _;

	# Slurp in the file
	local $/ = undef;
	open( CFG, $file ) or return $class->_error( "Failed to open file '$file': $!" );
	my $contents = <CFG>;
	close( CFG );

	$class->read_string( $contents );
}

# Create an object from a string
sub read_string {
	my $class = ref $_[0] ? ref shift : shift;
	my $self  = bless {}, $class;
	return undef unless defined $_[0];

	# Parse the file
	my $ns      = '_';
	my $counter = 0;
	foreach ( split /(?:\015{1,2}\012|\015|\012)/, shift ) {
		$counter++;

		# Skip comments and empty lines
		next if /^\s*(?:\#|\;|$)/;

		# Remove inline comments
		s/\s\;\s.+$//g;

		# Handle section headers
		if ( /^\s*\[\s*(.+?)\s*\]\s*$/ ) {
			# Create the sub-hash if it doesn't exist.
			# Without this sections without keys will not
			# appear at all in the completed struct.
			$self->{$ns = $1} ||= {};
			next;
		}

		# Handle properties
		if ( /^\s*([^=]+?)\s*=\s*(.*?)\s*$/ ) {
			$self->{$ns}->{$1} = $2;
			next;
		}

		return $self->_error( "Syntax error at line $counter: '$_'" );
	}

	$self;
}

# Save an object to a file
sub write {
	my $self = shift;
	my $file = shift or return $self->_error(
		'No file name provided'
		);

	# Write it to the file
	my $string = $self->write_string;
	return undef unless defined $string;
	open( CFG, '>' . $file ) or return $self->_error(
		"Failed to open file '$file' for writing: $!"
		);
	print CFG $string;
	close CFG;
}

# Save an object to a string
sub write_string {
	my $self = shift;

	my $contents = '';
	foreach my $section ( sort { (($b eq '_') <=> ($a eq '_')) || ($a cmp $b) } keys %$self ) {
		# Check for several known-bad situations with the section
		# 1. Leading whitespace
		# 2. Trailing whitespace
		# 3. Newlines in section name
		return $self->_error(
			"Illegal whitespace in section name '$section'"
		) if $section =~ /(?:^\s|\n|\s$)/s;
		my $block = $self->{$section};
		$contents .= "\n" if length $contents;
		$contents .= "[$section]\n" unless $section eq '_';
		foreach my $property ( sort keys %$block ) {
			return $self->_error(
				"Illegal newlines in property '$section.$property'"
			) if $block->{$property} =~ /(?:\012|\015)/s;
			$contents .= "$property=$block->{$property}\n";
		}
	}
	
	$contents;
}

# Error handling
sub errstr { $Config::Tiny::errstr }
sub _error { $Config::Tiny::errstr = $_[1]; undef }

1;

__END__