previous | top | next

Tell Me a Story Mommy


Logging Tells a Story

#!/usr/bin/perl

package HashFromFile;

# Used for testing and debugging
use Object;

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{filename} || 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);
   
    if (&LOG->is_debug()) { 
        &LOG->debug(
            "Hash before return is: " . Object->as_string(obj => $hash)
        );
    }
    &LOG->info("Exiting make()");
    return $hash;
}

1;


Email: bschmaus@combinenet.com