Archive for March, 2006

Dispatch Tables Further

Here is a snipit of code that I used to test the idea, the actual script is a little more complicated.


#!/usr/bin/perl -w
 
use strict;
use IO::File;
 
my $fh = new IO::File;
my $file = "text.txt";
my $newString;
my $opers = {
                'TX:'  => \&text,
                'END:' => \&end,
               };
 
if ($fh->open($file)) {
    my @file = < $fh>;
    foreach my $string(@file) {
        foreach my $key (keys %$opers){
            if ($string =~ /^$key/) {
                chomp($string);
                ($newString = $string) =~ s/^$key//;
                $opers->{$key}->($newString);
            }
        }
    }
}
 
sub text {
    my $in = shift;
    print $in
}
 
sub end {
    my $in = shift;
    print $in
}

It opens the file, reads it in and if the line begins with TX: or END: it passes the line to the approriate subroutine. I like it!

Dispatch Tables

I thought I had a really great idea. I thought I was bending a language to fit my needs. I was writing a bit of perl for work this evening and I wanted to avoid a bunch of crazy if/else stuff. So I had this idea. I would write a hash that contained keys that could match lines in a file and if they matched, the value would be a function to execute. I thought this was pretty slick (and maybe not possible). Eric was on the ball though and pointed out that I was talking about a Dispatch Table.

Rats! Not new, not inventive :)

However it’s still cool. Maybe I’ll post some code in the next few days that illustrates the idea for those of you that are unfamilar with the idea.

« Previous Page