Tcl lmap emulator

Problem this snippet solves:

The version of Tcl used as the basis for iRules, TMSH and iApps through version 11.5 (and probably later) does not have the tremendously useful lmap function. This procedure emulates much of that functionality with the same call signature.

Code :

# 

###############
#
# $rlist = _lmap varname $varlist $body
#
# Foreach member of $varlist, assign the value to the variable identified
# at 'varname', and execute $body in that context.  Return a list of
# the evaluations.
# iRule proc Source
# Define the proc named _lmap (the underscore is used in the event that, in the future, lmap becomes a supported method) in a separate iRule or tmsh library:

###############
proc _lmap { varname varlist body } {
    set _bbr {}
    foreach [subst $varname] $varlist {
        lappend _bbr [subst $body]
    }
    return $_bbr
}

# As the included procedure comment explains, _lmap takes a Tcl list, $varlist, and a code body, $body. For each element in $varlist, $body is executed, substituting the current element of $varlist for the value of the named variable varname. So far, this is exactly the same as foreach. However, on each iteration, it builds a list of the result from the execution of $body and returns that list.

# Example - In a TMSH script assume one wishes to create a firewall address-list that contains all self-IPs. This is one way to do so: 

cli script self_addr_list {

proc script::init {} {

    proc _lmap { varname varlist body } {
        set _bbr {}
        foreach [subst $varname] $varlist {
            lappend _bbr [subst $body]
        }
        return $_bbr
    }

}

proc script::run {} {
    set selfs [_lmap awm [_lmap so [tmsh::get_config /net self] { [tmsh::get_field_value $so "address"] }] { [lindex [split $awm /] 0] }]

    tmsh::create / security firewall address-list myself addresses replace-all-with \{ [join [_lmap ip $selfs { [format "$ip"] }] " "] \}
}

proc script::help {} {
}

proc script::tabc {} {
}

    total-signing-status not-all-signed
}
Published Mar 18, 2015
Version 1.0
No CommentsBe the first to comment