Ini.pm

Code Index:



NAME

ICD::Config::Ini - Simple reading from an INI file with preserved comments, too!


SYNOPSIS

 # INI file
 ; The name of the server block to use
 ; Use one of the blocks below.
 server = Server01
 ; All server blocks need a host and port.
 ; These should be under each block.
 [Server01]
 host=foo.bar.com
 port=7775
 ### PERL CODE
 use ICD::Config::Ini;
 my $conf = new ICD::Config::Ini;
 $conf->read('config.ini');
 $conf->dump();


DESCRIPTION


Very simplistic reading of INI files. A new object must be created
for each INI file (an object keeps all the data read in from an 
INI).


METHODS

new()

Creates a new ICD::Config::Ini object.

read($file)

Read data from INI file $file. The object's hashref will contain this INI file's contents.

dump()

Uses module Data::Dumper to dump entire object


SEE ALSO

IO::File, Data::Dumper, Perl


   1 package ICD::Config::Ini;
   2 
   3 use strict;
   4 use warnings;
   5 use IO::File;
   6 use Data::Dumper;
   7 
   8 sub new {
   9     my $class = shift;
  10     my $self  = {};
  11     bless $self, $class;
  12     return $self;
  13 }
  14 
  15 sub read {
  16     my ( $self, $file ) = @_;
  17     return unless -e $file;
  18     my $lines = $self->_read_lines($file);
  19     return $self->_parse($lines);
  20 }
  21 
  22 sub dump {
  23     my $self = shift;
  24     print Dumper $self;
  25 }
  26 
  27 sub _read_lines {
  28     my ( $self, $file ) = @_;
  29     my $fh = new IO::File $file, "r";
  30     if ( defined $fh ) {
  31         chomp( my @lines = <$fh> );
  32         $fh->close;
  33         return \@lines;
  34     }
  35     else {
  36 
  37         # Return empty ARRAY reference
  38         return [];
  39     }
  40 }
  41 
  42 sub _parse {
  43     my ( $self, $lines ) = @_;
  44     my $block = 'default';
  45     foreach my $line ( @{$lines} ) {
  46         $line = $self->_trim($line);
  47 
  48         # Found block definition
  49         if ( $line =~ /\s*\[(.*?)\]\s*/ ) {
  50             $block = $1;
  51             next;
  52         }
  53 
  54         # Skip comments
  55         next if $line =~ /^\s*\;/;
  56         next if $line =~ /^\s*\#/;
  57 
  58         # Skip empty lines
  59         next if length $line == 0;
  60 
  61         my ( $what, $is ) = split( /=/, $line, 2 );
  62         $what = $self->_trim($what);
  63         $is   = $self->_trim($is);
  64 
  65         $self->{"$block"}->{"$what"} = $is;
  66     }
  67     return 1;
  68 }
  69 
  70 sub _trim {
  71     my ( $self, $string ) = @_;
  72 
  73     $string =~ s/^\s*//g;
  74     $string =~ s/\s*$//g;
  75     $string =~ s/\r//g;
  76     $string =~ s/\n//g;
  77 
  78     return $string;
  79 }
  80 
  81 1;  
  82 __END__
  83