Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing arguments to a proc

Status
Not open for further replies.

julian9909

Technical User
Jan 15, 2010
1
EU
The following lines of code:-

set x "a b c"

foreach j $x {
puts $j
puts $x
}

produce the following result:

a
a b c
b
a b c
c
a b c



I would expect the following lines of code to
produce the same result.

proc srtlenlist {args} {
foreach j $args {
puts $j
puts $args
}
return $j
}

srtlenlist "a b c"


It actually produces the following:-

a b c
{a b c}

Can someone explains this?

thanks
julian9909




 
In the first case, the string, "a b c" is being treated as a list, implicitly split on spaces.

In the second case, the proc has a single argument which, again, is implicitly a list but in this case you passed a single string which is then interpreted in the proc as a list with a single element.

To achieve the desired (I assume) result, you should always explicitly create lists, in this case by split "a b c".

_________________
Bob Rashkin
 
I think a more proper answer lies in the fact that "args" is actually a tcl keyword and it has a very specific functionality that you need to understand. It is not just an argument place holder...it actually catches all remaining individual arguments not accounted for previous parameters in the signature of the proc.

In other words, args takes all remaining individual arguments and makes a list out of them...pay special attention to the "indivual" part...

so, when you call your proc with "a b c" you are actually passing a single argument, not three, after all you have grouped those space separated characters with quotes.

To achieve the same effect (if you want args to be a list of { a b c } , then you need to call your proc like this:

strlenlist a b c

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top