Reputation: 471
I have a sample proc
proc exam {return_value} {
set input "This is my world"
regexp {(This) (is) (my) (world)} $input all a b c d
set x "$a $b $c $d"
return x }
After the above proc execution i will get all a b c d value in single list, so if i want only b value from the above proc, now am doing [lindex [exam] 1]. I am looking for other way to get output in different manner instead of using lindex or returun_value(b) can give the my expected output
Upvotes: 0
Views: 10715
Reputation: 137567
The usual way of returning multiple values is as a list. This can be used with lassign
at the call site so that the list is broken into multiple variables immediately.
proc exam {args} {
set input "This is my world"
regexp {(This) (is) (my) (world)} $input all a b c d
set x "$a $b $c $d"
return $x
}
lassign [exam ...] p d q bach
You can also return a dictionary. In that case, dict with
is a convenient way to unpack:
proc exam {args} {
set input "This is my world"
regexp {(This) (is) (my) (world)} $input all a b c d
return [dict create a $a b $b c $c d $d]
}
set result [exam ...]
dict with result {}
# Now just use $a, $b, $c and $d
Finally, you can also use upvar
inside exam
to bring the caller's variables into scope, though there it's usually wisest to only do that with variables that the caller gives you the name of.
proc exam {return_var} {
upvar 1 $return_var var
set input "This is my world"
regexp {(This) (is) (my) (world)} $input all a b c d
set var "$a $b $c $d"
return
}
exam myResults
puts "the third element is now [lindex $myResults 2]"
Upvotes: 5
Reputation: 501
You can use dict
and choose such key-value mapping that will make your intent clear:
return [dict create width 10 height 200 depth 8]
I think there are no ways in Tcl to return multiple values other than compound data structures or yield
from a coroutine
.
Upvotes: 3