Monday, November 24, 2008

Event driven programming with Perl

By using hash table and function pointers you can implement an event dispatcher in Perl. With this programming style you can reduce conditions statements like if-else and switch.

#!/usr/bin/perl -w
use strict;

die "Syntax: test.pl action data\n" unless @ARGV > 1;

my %handlers;

$handlers{"up"} = \&OnUpper;
$handlers{"lo"} = \&OnLower;

die "Invalid ation!\n" unless exists $handlers{$ARGV[0]};

# The dispatcher
$handlers{$ARGV[0]}->($ARGV[1]);

sub OnUpper
{
  my $param = shift;
  print(uc "$param\n");
}

sub OnLower
{
  my $param = shift;
  print(lc "$param\n");
}