Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

9/23/2016

TclArrays

TclArrays
https://www.tutorialspoint.com/tcltk/tcl_arrays.htm
Copyrighttutorialspoint.com
Anarrayisasystematicarrangementofagroupofelementsusingindices.Thesyntaxfortheconventionalarray
isshownbelow.
setArrayName(Index)value

Anexampleforcreatingsimplearrayisshownbelow.
#!/usr/bin/tclsh
setlanguages(0)Tcl
setlanguages(1)"CLanguage"
puts$languages(0)
puts$languages(1)

Whentheabovecodeisexecuted,itproducesthefollowingresult
Tcl
CLanguage

SizeofArray
Thesyntaxforcalculatingsizearrayisshownbelow.
[arraysizevariablename]

Anexampleforprintingthesizeisshownbelow.
#!/usr/bin/tclsh
setlanguages(0)Tcl
setlanguages(1)"CLanguage"
puts[arraysizelanguages]

Whentheabovecodeisexecuted,itproducesthefollowingresult
2

ArrayIteration
Though,arrayindicescanbenoncontinuouslikevaluesspecifiedforindex1thenindex10andsoon.But,in
casetheyarecontinuous,wecanusearrayiterationtoaccesselementsofthearray.Asimplearrayiterationfor
printingelementsofthearrayisshownbelow.
#!/usr/bin/tclsh
setlanguages(0)Tcl
setlanguages(1)"CLanguage"
for{setindex0}{$index<[arraysizelanguages]}{incrindex}{
https://www.tutorialspoint.com/cgibin/printpage.cgi

1/3

9/23/2016

TclArrays

puts"languages($index):$languages($index)"
}

Whentheabovecodeisexecuted,itproducesthefollowingresult
languages(0):Tcl
languages(1):CLanguage

AssociativeArrays
InTcl,allarraysbynatureareassociative.Arraysarestoredandretrievedwithoutanyspecificorder.
Associativearrayshaveanindexthatisnotnecessarilyanumber,andcanbesparselypopulated.Asimple
exampleforassociativearraywithnonnumberindicesisshownbelow.
#!/usr/bin/tclsh
setpersonA(Name)"Dave"
setpersonA(Age)14
puts$personA(Name)
puts$personA(Age)

Whentheabovecodeisexecuted,itproducesthefollowingresult
Dave
14

IndicesofArray
Thesyntaxforretrievingindicesofarrayisshownbelow.
[arraynamesvariablename]

Anexampleforprintingthesizeisshownbelow.
#!/usr/bin/tclsh
setpersonA(Name)"Dave"
setpersonA(Age)14
puts[arraynamespersonA]

Whentheabovecodeisexecuted,itproducesthefollowingresult
AgeName

IterationofAssociativeArray
Youcanusetheindicesofarraytoiteratethroughtheassociativearray.Anexampleisshownbelow.
#!/usr/bin/tclsh
setpersonA(Name)"Dave"
setpersonA(Age)14
foreachindex[arraynamespersonA]{
puts"personA($index):$personA($index)"
}

Whentheabovecodeisexecuted,itproducesthefollowingresult
https://www.tutorialspoint.com/cgibin/printpage.cgi

2/3

9/23/2016

TclArrays

personA(Age):14
personA(Name):Dave

https://www.tutorialspoint.com/cgibin/printpage.cgi

3/3

You might also like