Updated 2014-09-10 06:30:46 by LAM

This dirty code simulates the function "array_pad" of other languages for example PHP (more info in array_pad on php)
proc array_pad { _arr size value} {
        foreach {a b} $_arr {
                lappend arr "$a $b"
        }
        set orig_len [llength $arr]
        set diff [expr abs($size) - $orig_len];
        if { $diff <= 0 } {
                return $_arr        
        }
        if {$size < 0 } {
                set  idx 0
                set sign -1
        } else {    
                set idx [expr $orig_len-1];
                set sign 1
        }        
        set pointer [ lindex [lsort -integer -index 0 $arr]  "$idx 0"]         
        for {set j 0 } {$j < $diff} {incr j} {
                set pointer [expr $pointer+$sign]
                lappend _arr $pointer $value
        }
        return  $_arr
}

Preconditions

  1. list must have even number of elements
  2. index must be integers

Usage

array set arr {0 12 1 10 2 9};
set larr [array get arr]
array set arr1 [array_pad $larr 5 0];
parray arr1
# PHP'esque (12, 10, 9, 0, 0)

array set arr2 [array_pad $larr -7 -1];
parray arr2
# (-1, -1, -1, -1, 12, 10, 9)

array set arr3 [array_pad $larr 2 "noop"];
parray arr3
# not padded