in reply to Re: How to call a Sub / Function with changing name
in thread How to call a Sub / Function with changing name

I have never heard of a dispatch table but I like it. I would like to pass a filehandle to the function but I have not gotten it to work. Can it be done? Can variables be passed?
my %function = ( allergies => sub { print_allergies ( my $var) }, immunizations => sub { print "in immunizations\n" }, ); my $dir = 'input_files'; die "can't opendir $!" unless opendir DIR, $dir; while (defined(my $file = readdir DIR)) { do { # print "The directory and file are $dir/$file\n"; die "Can't open input file $!" unless open IN, "< $dir/$file"; use File::Glob (); while (defined($_ = glob(' IN '))) { # print "Hello $_"; } # print_allergies (*IN); $function{$file}->() if exists $function{$file}; }; } closedir DIR; sub print_allergies{ local (*FH) = @_; while (<FH>){ next if (/^#/); print $_ ; } }
Allergy file looks like this
# Input file for allergies # Date, Diagnosed By, Type, allergy, reaction,specifics 2009-05-16,Children's Hospital Boston,drugs,penicillin,Blue rash,This +only happens on weekends 2009-05-17,Boston Medical Group,drugs,Vitamin B,Rash on torso,This hap +pens after 9PM 2009-05-17,Children's Hospital,food,Diary,Upset stomach and gas, Happe +ns after drinking whole milk

Replies are listed 'Best First'.
Re^3: How to call a Sub / Function with changing name
by ig (Vicar) on Oct 29, 2010 at 01:17 UTC

    You can pass variables and file handles to subroutines. See perlsub for details. Here is an example:

    use strict; use warnings; my %function = ( allergies => \&print_allergies, immunizations => sub { my ($fh, $dir) = @_; print "\nin immunizations from directory $dir\n"; }, ); my $dir = 'input_files'; opendir DIR, $dir or die "$dir: $!"; while (defined(my $file = readdir DIR)) { next if($file =~ /^\.+$/); print "The directory and file are $dir/$file\n"; open my $fh, '<', "$dir/$file" or die "$dir/$file: $!"; $function{$file}->($fh, $dir) if exists $function{$file}; } closedir DIR; sub print_allergies{ my ($fh, $dir) = @_; print "\nprinting allergies from directory $dir\n"; while (<$fh>){ next if (/^#/); print $_ ; } }

    update: added example of passing a variable other than a file handle.

      Thanks! This is what I did not have correct.
      $function{$file}->($fh, $dir) ... allergies => \&print_allergies
      Thanks very much!