Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Complex if/else or case logic

by graff (Chancellor)
on Mar 18, 2014 at 02:59 UTC ( #1078719=note: print w/replies, xml ) Need Help??

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).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1078719]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2016-10-22 07:16 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (292 votes). Check out past polls.