Getting started with Tcl: example 13

This page is part of the Airplug documentation related to Tcl/Tk.
Back to the Tcl/Tk documentation page / Back to the Airplug documentation page

How to scan an array

Script

  • Using for in case of numerical index:
    #!/usr/bin/tclsh
    # Scanning arrays using for
     
    set tableau(1) un
    set tableau(2) deux
    set tableau(3) trois
     
    for {set i 1} { $i <= 3 } {incr i} {
      puts stdout "tableau($i) = $tableau($i)"
    }
  • Using foreach key and array names
    #!/usr/bin/tclsh
    # Scanning arrays using foreach and array names
     
    set tableau(1) un
    set tableau(2) deux
    set tableau(3) trois
     
    foreach key [array names tableau] {
      puts stdout "tableau($key) = $tableau($key)"
    }
  • A variant, using foreach and array get:
    #!/usr/bin/tclsh
    # Scanning arrays using foreach key 
    set tableau(1) un
    set tableau(2) deux
    set tableau(3) trois
     
    foreach { key value } [array get tableau] {
      puts stdout "tableau($key) = $value"
    }
  • Using array anymore for efficient searching in large arrays:
    #!/usr/bin/tclsh
    # Scanning arrays using foreach key 
    set tableau(1) un
    set tableau(2) deux
    set tableau(3) trois
     
    set wanted [array startsearch tableau]
    while {[array anymore tableau $wanted]} {
      set key [array nextelement tableau $wanted]
      puts stdout "tableau($key) = $tableau($key)"
    }
    array donesearch tableau $wanted

Output

tableau(1) = un
tableau(2) = deux
tableau(3) = trois

<br/>


This page is part of the Airplug documentation related to Tcl/Tk.
Back to the Tcl/Tk documentation page / Back to the Airplug documentation page

 
Back to top
en/doc/pub/tcltk/example-13.txt · Last modified: 2017/04/05 16:16 (external edit)
 
 
Driven by DokuWiki