TCL : Concatenate a variable and a string
Asked Answered
P

6

21

Assume we have a variable 'a' set to 12345 :

set a 12345

Now how do i set a new variable 'b' which contains the value of 'a' and another string say 9876

workaround is something like

set a "12345"
set u "9876"

set b $a$u

but i dont want to specify $u instead i want the direct string to used..

Phocine answered 9/3, 2011 at 5:57 Comment(0)
I
39

You can do:

set b ${a}9876

or, assuming b is either set to the empty string or not defined:

append b $a 9876

The call to append is more efficient when $a is long (see append doc).

Inconvenient answered 9/3, 2011 at 6:46 Comment(6)
Hey Trey, good answer. Is it better to use double quotes in these cases, or does it make no odds? E.g. set b "${a}9876"Dwight
@Brian: Tcl doesn't care, but you might want to do that if it makes for prettier formatting.Hannis
you would only require grouping of some sort if you were trying to concat something with a space in it, depending on whether you also need variable substitution {} or "" would be neededSmithereens
There is also the join command, but this is intended mainly for strings with strings--as far as I understand it.Genetics
@Genetics To use the join command you'd need to make a list, something like set b [join [list $a "9876"] ""]Inconvenient
Thanks for the clarification, @TreyJackson. I was missing that information.Genetics
V
7

other option is to use set command. since set a gives value of a we can use it to set value of b like below

set b [set a]9876

Verina answered 9/3, 2011 at 18:9 Comment(0)
N
4

Or,you can use format

set b [format %s%s $a $u]

Nomarchy answered 17/12, 2014 at 8:12 Comment(0)
H
3

From Tcl 8.6.2 onwards, there is string cat which can be used to solve this problem.

set b [string cat $a 9876]
Hannis answered 13/12, 2014 at 8:25 Comment(0)
W
1

Other option is to use concat command like below.

set b [concat $a\9876]

Woodrowwoodruff answered 20/9, 2013 at 6:57 Comment(0)
S
0

I don't get what you mean the direct string... I'm not sure if you want... However, if you want the value of 12349876 you can do:

% set b [concat $a$u]
12349876

If you want $a or $u to be part of the string, just add a backslash '\' before the desired variable.

Summertime answered 18/11, 2014 at 18:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.