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..

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
user651006
  • 213
  • 1
  • 2
  • 5

6 Answers6

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).

Trey Jackson
  • 73,529
  • 11
  • 197
  • 229
  • 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"` – TrojanName Mar 09 '11 at 10:14
  • 3
    @Brian: Tcl doesn't care, but you might want to do that if it makes for prettier formatting. – Donal Fellows Mar 09 '11 at 10:19
  • 2
    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 needed – jk. Mar 09 '11 at 10:35
  • 1
    There is also the `join` command, but this is intended mainly for strings with strings--as far as I understand it. – Raj Oct 18 '16 at 02:55
  • 1
    @Raj To use the `join` command you'd need to make a list, something like `set b [join [list $a "9876"] ""]` – Trey Jackson Oct 19 '16 at 15:34
  • Thanks for the clarification, @TreyJackson. I was missing that information. – Raj Oct 19 '16 at 23:18
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

vaichidrewar
  • 9,251
  • 18
  • 72
  • 86
4

Or,you can use format

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

Harry Lee
  • 992
  • 8
  • 7
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]
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
1

Other option is to use concat command like below.

set b [concat $a\9876]

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.

aLt
  • 48
  • 5