previous | top | next

Perldoc Will Make You Feel Good


Developers get their expectations from the API docs

#!/usr/bin/perl

package HashFromFile;

# Used for testing and debugging
use Object;

=head1 NAME

HashFromFile

=head1 SYNOPSIS

Creates a hash from an input file.

my $hash = HashFromFile->make(filename => '/path/to/input_file.txt');

=head1 DESCRIPTION

This module reads input from a file and builds a hash from the data in the
file.  This module requires that the input file be formatted very
specifically.  Each line should start with a value that will be used as a key
of the hash.  This must be followed by a ':', which must be followed by another
value that will be the element of the hash for that key.  Spaces are not
allowed on either side of the ':'.  Empty lines are okay.

Example:

  Favorite Food:Beer
  Favorite Sport:Curling

=head1 make

Title:     make

Usage:     my $hash = HashFromFile->make(filename => '/path/to/file.txt');

Function:  Reads input from a file and builds a hash.

Arguments: filename - Path to file that contains input for the hash.

Returns:   Hash reference.

=cut

sub make {
    &LOG->info("Entering make()");
    my ($class, %args) = @_;

    # The text file that provides the input for the hash we're going to create
    my $file = $args{file} || undef;
    if (defined $file) {
        &LOG->debug("Using file: '$file' as data source");
    }
    else {
        &LOG->logdie("Exiting because no file was specified");
    }
    
    # Init hash reference that will be populated with data read from $file
    my $hash = {};

    # Open readonly
    open(FH, "< $file")
        or &LOG->logdie("Could not open file '$file': $!");
    
    while (my $line = <FH>) {
        if ($line =~ /^\s+$/) {
            &LOG->debug("Current line was empty, skipping to next line");
            next;
        }
        else {
            &LOG->debug("Current line has data: $line");
        }
        
        chomp($line);

        if ($line !~ /:/) {
            &LOG->warn("Current line does not contain required delimiter ':'");
        }

        # Split each line into a list by the ':' character, only the words
        # around the first encountered ':' are used
        my ($key, $value) = split(/:/, $line);

        &LOG->debug("Adding new entry to hash, key: $key - value: $value");
        $hash->{$key} = $value;
    }

    close(FH);
   
    &LOG->debug("Hash before return is: " . Object->as_string(obj => $hash));
    &LOG->info("Exiting make()");
    return $hash;
}

1;


Email: bschmaus@combinenet.com