Forum Discussion

Dan_103700's avatar
Dan_103700
Icon for Nimbostratus rankNimbostratus
Mar 11, 2011

Nested Conditionals and NOT conditionals

Hi there,

 

 

I've been meaning to ask for awhile how to do nested conditionals and use a "not" operator in iRules.

 

 

I frequently end up writing iRules that look like this:

 

 

if { $foo starts_with "bar" } {

 

Do Nothing

 

} else {

 

pool foo_pool

 

}

 

 

Would I get the same thing with just:

 

 

if { not $foo starts_with "bar" } {

 

pool foo_pool

 

}

 

 

Also, is it possible to do nested conditionals... something like:

 

 

if { {$foo starts_with "bar" or $bar ends_with "foo"} and {$baz == 5} } {

 

 

And ideally, combine these 2 to get something like:

 

 

if { { {not $foo starts_with "bar"} or $bar ends_with "foo"} and {$baz == 5} } {

 

 

I guess if I take the time to learn the operator precedence and how conditional comparisons evaluate from left to right, I wouldn't need the extra nesting. Still, as a programmer, I've always found value in adding extra parenthesis to make conditional logic easier to read. Hopefully, there's some similar syntax in Irules/TCL to do this because trying to program without the extra braces/parenthesis makes my head hurt.

 

 

Thanks!

 

-Dan

 

4 Replies

  • Hi Dan,

    Make sure to use parentheses (not curly braces) when negating checks. Else, you'll get syntax errors or the wrong tests performed:

    
    if { not ($foo starts_with "bar") } {
       pool foo_pool
    }
    

    Without the parens, you'd be negating $foo and then seeing if that starts with "bar".

    Aaron
  • Colin did a good overview on nested conditionals here - http://devcentral.f5.com/Tutorials/TechTips/tabid/63/articleType/ArticleView/articleId/255/iRules-101--13--Nested-Conditionals.aspx

     

     

    I personally like using "!" for not.
  • TCL operator precedence should be the same as most other languages. So the ! or not takes precedence over the starts_with string evaluation.

     

     

    http://www.tcl.tk/man/tcl8.4/TclCmd/expr.htmM6

     

     

    if { {$foo starts_with "bar" or $bar ends_with "foo"} and {$baz == 5} } {

     

    ->

     

    if { ($foo starts_with "bar" or $bar ends_with "foo") and ($baz == 5) } {

     

     

    if { { {not $foo starts_with "bar"} or $bar ends_with "foo"} and {$baz == 5} } {

     

    ->

     

    if { ( not ($foo starts_with "bar") or $bar ends_with "foo") and $baz == 5 } {

     

     

    Aaron
  • Great info. I have a feeling I'll be cleaning up some of my messier work, come Monday. Thanks.