Forum Discussion

dragonflymr's avatar
dragonflymr
Icon for Cirrostratus rankCirrostratus
Dec 10, 2015

proc - how to interpret

Hi,

I am puzzled what is exact purpose of char declaration in proc below (from

proc randomNumberGenerator {length {chars "0123456789"}} {
  set range [expr {[string length $chars]-1}]
  set txt ""
  for {set i 0} {$i < $length} {incr i} {
    set pos [expr {int(rand()*$range)}]
    append txt [string range $chars $pos $pos]
  }
  return $txt
}

(from article)

I assume that char is receiving value (10) passed to proc via: set x [call library::randomNumberGenerator 10]. But what length {chars "0123456789"} is exactly doing here?

Piotr

3 Replies

  • Hi Piotr,

    "0123456789" is the default value for "chars" if not passed explicitly. In the end, the proc can be called by using either:

    [call library::randomNumberGenerator 10]

    or

    [call library::randomNumberGenerator 10 12345]

    Cheers, Kai

  • Thanks for answer, sorry for stupid questions but I am not so experienced in programming at all.

     

    So what exactly it means length {chars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"} - that is declaration what kind of characters can be used for generating random number?

     

    What confuses me in above what is purpose of using length? So how 10 in call library::randomNumberGenerator 10 is passed and used by proc? I assumed that 10 passed to proc is defining how long random string should be?

     

    Or I am just confused by length - it's not function but var that is used to receive 10 when call is performed?

     

    Piotr

     

  • Hi Piotr,

     

    the proc simply outputs "$length" times a "rand()" position from "$chars". So any alphanumeric charater may be used as input.

     

    Cheers, Kai