in reply to Multiple If Selections

As McDarren mentioned, a dispatch table is probably the way to go, and you can make it as complex or as simple as you wish (depending on your data). See below for a couple of examples.

use strict; use warnings; my %dispatch = ( Job => \&job, File => \&file, Image => \&image, # Job => \&add_to_hash, # alternative to job/image subs ); my %job_details_info; my @files; foreach my $line ( 'Job line', 'File line', 'Image line' ) { # use a dispatch table if( $line =~ m/(Job|File|Image)/ ) { $dispatch{$1}->($line); } # group functionality if( $line =~ m/(Job|Image)/ ) { $job_details_info{$1} = $line; } elsif( $line =~ m/File/ ) { push @files, $line; } } sub job { my ( $line ) = @_; $job_details_info{Job} = $line; } sub file { my ( $line ) = @_; push @files, $line; } sub image { my ( $line ) = @_; $job_details_info{Image} = $line; } # you could combine the job and image subs into something like this sub add_to_hash { my ( $key, $line ) = @_; $job_details_info{$key} = $line; }

Replies are listed 'Best First'.
Re^2: Multiple If Selections
by dsheroh (Monsignor) on Jan 07, 2008 at 17:46 UTC
    If you're going to go with this approach to setting up/executing the dispatch, one suggestion:

    Change

    if( $line =~ m/(Job|File|Image)/ )
    to
    my $re = join '\|', keys %dispatch; if ( $line =~ m/$re/ )
    so that you won't have to manually update the regex every time a case is added/removed/renamed. Changing the dispatch table and forgetting to update that regex would otherwise seem like a very easy way to introduce bugs which will leave you scratching your head for hours as you stare at the dispatch table and the called sub trying to figure out why they don't work together.

      Excellent suggestion++. You forgot the capturing parentheses, though, so instead of wondering why the dispatch table and the subs are working together you'll be wondering why $1 isn't what you think it is. :-)

      Change

      my $re = join '\|', keys %dispatch; if( $line =~ m/$re/ )
      to either
      my $re = '(' . join( '|', keys %dispatch ) . ')'; if( $line =~ m/$re/ )
      or
      my $re = join( '|', keys %dispatch ); if( $line =~ m/($re)/ )