http://www.perlmonks.org?node_id=1078719


in reply to Complex if/else or case logic

Let's suppose you could structure each email message as a hash, where the keys are things like "sender", "subject", "body", etc (as needed to handle whatever conditions you use to identify "kinds" of messages).

Then, you could structure your inventory of "kinds" as lists of conditions to be satisfied - e.g.:

my %kinds = ( type1 => { sender => qr/^me$/, subject => qr/this/, body => qr/tha +t/ }, type2 => { sender => qr/^you$/, subject => qr/these/, body => qr/t +hose/ }, # ... ); sub classify_msg { my ( $msg ) = @_; # $msg is expected to be a hash ref my @matches = (); for my $type ( keys %kinds ) { my $matched = 1; for my $test ( @{$kinds{$type}} ) { $matched &= ( $$msg{$test} =~ $kinds{$type}{$test} ); last unless $matched; } push @matches, $type if ( $matched ); } return \@matches; }
(not tested - updated to add a missing close-curly in the second "for" statement, and to use curlies instead of square brackets when assigning anon.hashes to keys in %kinds)

This assumes a given message could meet the conditions for more than one "kind". It also assumes that regex matching will always be an appropriate tool for testing the various conditions (but you could elaborate the "kinds" structure to handle other types of tests).