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

<html><br/></html>


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: by 127.0.0.1
 
 
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0