0

How to store a command line arguments in an array in tcl?

I'm trying to store command line arguments (argv) in an array. Is argv is not array? I tried the following code but doesn't work for me.

proc auto args {
    global argv
    set ifname [lindex $argv 0]
    puts "***********$ifname"
    puts "$argv(2)"
    for { set index 1} { $index < [array size argv ] } { incr index } {
       puts "argv($index) : $argv($index)"
    }
}
#Calling Script with arguments
auto {*}$argv
2
  • In Tcl terms, argv is a list not an array, so you would use lindex to access its elements and llength to find its size. Commented Aug 12, 2016 at 8:41
  • Note that in tcl, the word array does not mean array in other languages. Are you sure you want an array and not a list? Even if you're sure you want a key->value pair data structure, are you sure you want an array and not a dict? Commented Aug 12, 2016 at 9:03

1 Answer 1

3

Tcl's argv global is a list, not an array, because order matters and lists are an entirely reasonable way of doing the arguments. That's why you use lindex (and other list operations) with it. You can convert to an array, but most code will end up “surprised” by that. As such, it's better to use a different array name for that (“arguments” below):

proc argumentsToArray {} {
    global argv arguments
    set idx 0
    unset -nocomplain arguments; # Just in case there was a defined variable before
    array set arguments {};      # Just in case there are no arguments at all
    foreach arg $argv {
        set arguments($idx) $arg
        incr idx
    }
}

argumentsToArray
puts "First argument was $argument(0) and second was $argument(1)"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.