[Denver-pm] Dispatch Lists?

Stuart A Johnston saj at thecommune.net
Tue Apr 19 16:17:01 PDT 2016


Here's a simple example. I've just used $ARGV[0] as the input but you 
could add another loop for your multi-line input.

#!/usr/bin/perl

use strict;
use v5.10;

sub sub_foo {
     say "foo: $_[0]";
}

sub sub_bar {
     say "bar: $_[0]";
}

my @dispatch = (
     [ qr/foo/, \&sub_foo ],
     [ qr/bar/, \&sub_bar ],
);

foreach my $d (@dispatch) {
     my ($r, $sub) = @$d;

     if ($ARGV[0] =~ $r) {
         $sub->($ARGV[0]);
         next;
     }
}



On 04/19/2016 02:28 PM, Robert L. Harris wrote:
>
> Anyone have a straight forward script using dispatch lists?  I have one
> ( 4500 lines by now ) which effectively does this:
>
>  1. Open input file
>  2. while<input> {
>  3.      $Line=<INPUT>
>  4.      &Sub1("Line") if ( $Line =~ /<regex pattern 1>/ );
>  5.      &Sub2("Line") if ( $Line =~ /<regex pattern 2>/ );
>  6.      &Sub3("Line") if ( $Line =~ /<regex pattern 3>/ );
>  7.      ... about 25 patterns now ...
>  8. }
>
> Yeah, it's ugly, it started out as a 30 line data munger about 2.5 years
> ago and I'm looking to speed and clean it up.   Each Sub performs
> various actions based which can't be simplified or condensed more than
> they have.
>
>     I've created my DispatchHash for subs/patterns but I think I'm
> confusing myself on actually doing the match and dispatch including
> passing $Line to the sub.
>
> Any examples would be very welcome.
>
> Robert



More information about the Denver-pm mailing list