Tuesday 13 December 2016

TCL-Arrays with Examples

•       Used to group multiple strings together in a single variable
•       Specified by a variable name followed by an index enclosed in parentheses.
         –          set my_array(1) value
         –          set my_array(one) another_value
•       Multidimensional arrays can be simulated
•       array names
 Returns a list of the indexes for all values stored in the array named 

Array Commands:         
•       array set
         –          Initialize an array 
•       array names
         –          Returns all array index
•       parray
         –          Print array
•       array unset
         –          Un-initialize the array 
•       array exists
         –          Returns 1 is varName is an array, 0 otherwise
•       array size
         –          Returns number of elements in the array


Tcl Array – Examples
% array set arrayVar \
                { 1 one 2 two 3 three }
% parray arrayVar
arrayVar(1) = one
arrayVar(2) = two
arrayVar(3) = three
% set arrayVar(4) four
four
% parray arrayVar
arrayVar(1) = one
arrayVar(2) = two
arrayVar(3) = three
arrayVar(4) = four

% array names arrayVar
4 1 2 3
% array exists arrayVar
1
% set name gaurav
gaurav
% array exists name
0
% array size arrayVar
4
% array unset arrayVar
% parray arrayVar
"arrayVar" isn't an array
%



A Tcl array is a collection of variables. Each variable may hold any value and the array is indexed by arbitrary values. The key-value pairs are unordered. A Tcl array is an associative array.
  
Creating arrays:

Tcl arrays can be created with the set or array set commands.

EXAMPLE 1:
#!/usr/bin/tclsh
set names(1) Jane
set names(2) Tom
set names(3) Elisabeth
set names(4) Robert
set names(5) Julia
set names(6) Victoria

puts [array exists names]      àprints 1
puts [array size names]         à prints 6

puts $names(1)                      ->prints Jane
puts $names(2)                      ->prints Tom
puts $names(6)                      ->prints Victoria


We create an array called names. The numbers are keys and the names are values of the array.

set names(1) Jane
In this line we set a value Jane to the array key 1. We can later refer to the value by the key.

puts [array exists names]
The array exists command determines whether the provided argument is an array.

puts [array size names]
We get the size of the array with the array size command.


EXAMPLE2:
#!/usr/bin/tclsh
array set days {
    1 Monday
    2 Tuesday
    3 Wednesday
    4 Thursday
    5 Friday
    6 Saturday
    7 Sunday
}

set n [array size days]

puts $days(1)                              àPrints Monday
puts "array has $n elements"      àPrints  array has 7 elements


Arrays are collections of variables:

Unlike in lists or dictionaries, items in arrays are variables. This means that we can make references to them.

#!/usr/bin/tclsh
array set days {
    1 Monday
    2 Tuesday
    3 Wednesday
    4 Thursday
    5 Friday
    6 Saturday
    7 Sunday
}

upvar #0 days(1) mon
upvar #0 days(2) tue
upvar #0 days(3) wed

puts $mon        prints à Monday
puts $tue          prints à Tuesday
puts $wed        prints à Wednesday



In the script three variables of the days array are referenced with the upvar command.

upvar #0 days(1) mon

The mon variable references the variable indexed with 1. The first argument of the upvar command is the uplevel, where #0 means the toplevel. That is, both the days array and the mon variable reside in the same global namespace.


 The array get command
The array get command returns a list containing pairs of elements of the array.
#!/usr/bin/tclsh
array set days {
    Peter 34
    Jane 17
    Lucy 28
    Mark 43
    Anthony 36
}

puts [array get days]

The example creates an array and prints its key-value pairs with the array get command.

Traversing arrays:
In the following examples, we will show how to traverse arrays.
#!/usr/bin/tclsh
array set days {
    1 Monday
    2 Tuesday
    3 Wednesday
    4 Thursday
    5 Friday
    6 Saturday
    7 Sunday
}
foreach {n day} [array get days] {
    puts "$n -> $day"
}
The example creates an array and prints its key-value pairs with the array get command.
The array get command returns a list of key, value elements, which can be iterated with the foreachcommand.

Removing elements:
In the last example of this chapter, we will show how to remove elements from the array
#!/usr/bin/tclsh
set names(1) Jane
set names(2) Tom
set names(3) Elisabeth
set names(4) Robert
set names(5) Julia
set names(6) Victoria
puts [array size names]
unset names(1)
unset names(2)

puts [array size names]

We create a names array. We use the unset command to remove items from the array. We check the size of the array before and after we remove the two items.
set names(1) Jane
The set command is used to create an item in the array.
unset names(1)
We use the unset command to remove an element with key 1 from the array.

EXAMPLES:

#Create array and print all elements in array
array set arrayvar {1 one 2 two 3 three}
puts [parray arrayvar]
puts [array names arrayvar]
puts [array size arrayvar]
puts [array get arrayvar]
puts [array exists arrayvar]

  
# Used as a one dimensional array
for { set i 0 } { $i < 8 } { incr i } {
  set base($i) $i
  puts "base($i) = $base($i)"
}

Output:
base(0) = 0
base(1) = 1
base(2) = 2
base(3) = 3
base(4) = 4
base(5) = 5
base(6) = 6
base(7) = 7
  
 # Used as a two dimensional array
# NOTE: "$i,$j" is a single string which is the index like "0,1"
for { set i 0 } { $i < 3 } { incr i } {
  for { set j 0 } { $j < 3 } { incr j } {
    set base($i,$j) $i
    puts "base($i,$j) = $base($i,$j)"
  }
}

Output:
base(0,0) = 0
base(0,1) = 0
base(0,2) = 0
base(1,0) = 1
base(1,1) = 1
base(1,2) = 1
base(2,0) = 2
base(2,1) = 2
base(2,2) = 2

Example:  
array set arr [list {1} {hari} {2} {Rajesh} {3} {Ram}]
foreach id [array names arr] {
puts "$arr($id) has ID No : $id"
}
if {[array exists arr]} {
puts "Array Exists"
} else {
puts "Array Does Not Exists"
}

puts "Total Array Items are : [array size arr]"
puts "Array Numbers in list are : [array names arr]"
puts "Name of persons in the arraylist are : $arr(1) $arr(2) $arr(3)"



TCL Lists and Arrays
TCL has many facilities for manipulating lists, which are collections of items separated by whitespace. For example, "llength" returns the number of items in
a list, "lindex" returns the Nth item in a list starting at item 0, "lrange" returns a range of items from a list, and "lsearch" returns the location of a
list item that matches a given value:

% set days "Mon Tue Wed Thu Fri Sat Sun"
Mon Tue Wed Thu Fri Sat Sun
% llength $days
7
% lindex $days 0
Mon
% lindex $days 1
Tue
% lrange $days 3 5
Thu Fri Sat
% lrange $days 5 end
Sat Sun
% lsearch $days Wed
2

The variables we have seen so far are examples of TCL "scalar" variables, which store a single text value. The text value might be a single numeric item, or
a whitespace-separated collection of items of any length TCL also includes associative arrays which allow many values to be assigned to a variable
according to an array index. In the case of many programming languages such as C, an array index will be one or more integer numbers. However in TCL, the
array index can be any text value.This is a powerful feature for organizing data, and it also allows us to simulate the use of conventional
multidimensional arrays in TCL.

TCL array variables are specified by an array name and an array index in ( ) parenthesis.As noted, the array index can be any text value, numeric or
otherwise. The assigned value can also be any text value, numeric or otherwise For example:

set monthInfo(1) Jan
set monthInfo(2) Feb

set dayInfo(30) "Sep Apr Jun Nov"
set dayInfo(31) "Jan Mar May Jul Aug Oct Dec"
set dayInfo(28) "Feb"

set mass(H) 1.0
set mass(He) 4.0
set mass(C) 13.0

Values of an array variable are extracted using $ dollar-sign substitution, as with scalar variables. The interesting detail is that the array index ca
also be specified in terms of a TCL expression. So, given the definitions above, from the nmrWish command line:

% puts $dayInfo(30)
Sep Apr Jun Nov

% puts $monthInfo([expr 1 + 1])
Feb

% set atom He
He
% puts $mass($atom)
4.0

To simulate a conventional multidimensional array, we can use a TCL array index composed of one or more integers, usually separated by a character such as
the "," comma.For example, we can build an array index which simulates a three-dimensional matrix location, by using three integer values to create the
index:

set ix 0
set iy 0
set iz 0
set a($ix,$iy,$iz) 1.14

Note again that the TCL array index is interpreted as an exact text value, not as a numeric one.So, space characters, decimal points, etc., change the
interpretation of the array index. In the example above, the array index is the exact five-character text value "0,0,0"for another example, the
following cases all refer to different array elements:

$m(1)
$m(1.0)
$m(1.00)
$m( 1)
$m(001)

The standard TCL command "info exists" can be used to test whether or not a given array value has been defined.

ARRAYS:
The syntax for an associative array is to put the index within parentheses:
set name(first) "Mary"
set name(last)  "Poppins"

puts "Full name: $name(first) $name(last)"
There are several array commands aside from simply accessing and creating arrays which will be discussed in this and the next lesson.
array exists arrayName
Returns 1 if arrayName is an array variable. Returns 0 if arrayName is a scalar variable, proc, or does not exist.
array names arrayName ?pattern
Returns a list of the indices for the associative array arrayName. If pattern is supplied, only those indices that match pattern are returned. The match is done using the globbing technique from string match.
array size arrayName
Returns the number of elements in array arrayName.
array get arrayName
Returns a list in which each odd member of the list (1, 3, 5, etc) is an index into the associative array. The list element following a name is the value of that array member.
array set arrayName dataList
Converts a list into an associative array. DataList is a list in the format of that returned by array get. Each odd member of the list (1, 3, 5, etc) is an index into the associative array, and the list element following that is the value of that array member.
array unset arrayName ?pattern?
Unsets all of the elements in the array. If pattern exists, only the elements that match pattern are unset.

Convert list to array:
set lst "1 2 3 4"
array set name $lst
puts [array get name]
=================================================
Example for using unset ini array
set info(name) "shiva prasad"
set info(age) "31"
foreach index [array name info] {
puts "$index = $info($index)"
}
puts [array size info]
puts [array unset info age]
foreach index [array name info] {
puts "$index = $info($index)"
}
puts [array size info]
output:
age = 31
name = shiva prasad
2
name = shiva prasad

1

No comments:

Post a Comment

Note: only a member of this blog may post a comment.