Aniket
Aniket

Reputation: 125

Write a procedures in TCL with dynamic variable

I am new to TCL and was trying to write a TCL procedure which take dynamic value. Like I want to pass n number of interface and vlan pair to the proc.

proc proc_data {device, intf_in, intf_out, args} {
foreach vlan $args {
    set inter_vlan [$device exec "show interface $intf_in $vlan"]
    set inter_vlan [$device exec "show interface $intf_out $vlan"]
    ....
         }
}

Is there any way I can pass :

{ device [interface vlan] <<<<< dynamic no of pair

Upvotes: 0

Views: 886

Answers (3)

Mr. Bordoloi
Mr. Bordoloi

Reputation: 80

the answer you have posted is not very efficient. The logic you have used will check all the interfaces one by one and check all the vlans for each interface.

What if you need to check a particular vlan set instead of all the vlans for a few interfaces?

Upvotes: 0

Aniket
Aniket

Reputation: 125

Thanks @Donal Fellows

Posting the code I was looking for:

proc data_proc {device intr vlan} {
puts "Logged in device is: $device"
foreach a $intr {
    set interface [$device "show interface $a"
    foreach b $vlan {
    set inter_vlan [$device "show interface $a vlan $b"
    }
  }
}
data_proc device {interface1 interface2 ...} {vlan1 vlan2 ...}

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137627

It depends on how you want to map the arguments, but the key commands are likely to be foreach and lassign.

The foreach command can consume several values each time through the loop. Here's a simple example:

proc foreachmultidemo {args} {
    foreach {a b} $args {
        puts "a=$a, b=$b, a+b=[expr {$a+$b}]"
    }
}
foreachmultidemo 1 2 3 4 5 6

You can also iterate over two lists at once (and yes, this mixes with the multi-variable form if you want):

proc foreachdoubledemo {list1 list2} {
    foreach a $list1 b $list2 {
        puts "a=$a, b=$b, a+b=[expr {$a+$b}]"
    }
}
foreachdoubledemo {1 2 3} {4 5 6}

The lassign command can take a list and split it into variables. Here's a simple example:

proc lassigndemo {mylist} {
    foreach pair $mylist {
        lassign $pair a b
        puts "a=$a, b=$b, a+b=[expr {$a+$b}]"
    }
}
lassigndemo {{1 2} {3 4} {5 6}}

I'm not quite sure how to make these do what you're after, but it is bound to be one or the other, possibly in a mix.

Upvotes: 1

Related Questions