Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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]
[stevieb]: very interesting XS question over on SO

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2017-08-20 18:04 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (317 votes). Check out past polls.