Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

RE: rule base (comma operator / 'switch' construct)

by Russ (Deacon)
on Aug 30, 2000 at 02:47 UTC ( [id://30232]=note: print w/replies, xml ) Need Help??


in reply to How to write a nice rule base?

The "Found = in Conditional" warning was not from the tertiary, but the logical and. Since you are not really doing a logical test, but just combining statements, I would use the comma operator, here.
$allowed{action} = 'post|edit|delete|long|short'; $query->{action} eq "post" ? (($allowed{msgid} = '^(\d+|new)$'), ($allowed{data} = '^(([^|+]*[^|]+.*\|){4}[^|+]*[^|]+.*)$')) : 1; $query->{action} eq "edit" ? ($allowed{msgid} = '^(\d+|new)$') : 1; $query->{action} eq "delete" ? ($allowed{msgid} = '^(\d+)$') : 1; $query->{action} eq "long" ? (($allowed{sort} = '^(author|date|subject|expire)$'), ($allowed{msgid} = '^(\d*|all)$')) : 1; $query->{action} eq "short" ? (($allowed{sort} = '^(author|date|subject|expire)$'), ($allowed{msgid} = '^(\d+|all)$')) : 1; foreach $key (keys %$query){ exists $allowed{$key} ? 1 : return 0; return 0 if $query->{$key}!~/$allowed{$key}/; 1; }

Now, that said, here's another way to handle this:

# Map keys to coderefs (used sort of like a switch statement) my %ActionMap = (post => sub{ $allowed{msgid} = '^(\d+|new)$'; $allowed{data} = '^(([^|+]*[^|]+.*\|){4}[^|+]*[^|]+.*)$'; }, edit => sub{ $allowed{msgid} = '^(\d+|new)$'; }, delete => sub{ $allowed{msgid} = '^(\d+)$'; }, long => sub{ $allowed{sort} = '^(author|date|subject|expire)$'; $allowed{msgid} = '^(\d*|all)$'; }, short => sub{ $allowed{sort} = '^(author|date|subject|expire)$'; $allowed{msgid} = '^(\d+|all)$'; }); # "Call" the coderef matching the "switch" value $ActionMap{$query->{action}}->(); for my $key (keys %$query){ return 0 unless exists $allowed{$key} && $query->{$key} =~ /$allowed +{$key}/; }
Notes:
  • I'm concerned about the for loop. It looks like $query->{$key} will never match /$allowed{$key}/. This was just a code example, though, so...
  • This "switch" construct avoids your void-context values. The ternary may feel easier to read, but it leaves the reader wondering what you are doing with that 1 in each ternary.
  • There are, of course, other ways to do "switch" statements...this is merely one of them.

Russ
Brainbench 'Most Valuable Professional' for Perl

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2024-04-23 17:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found