1

I have a script say, myscript.tcl. The script will go through a file and do some basic operations. But I dont want to hardcode the file name inside the script with something like "open myfile.txt". I want to be able to pass different files to the script from the command line while running. How do I achieve this? Please help.

0

2 Answers 2

4

All the arguments to tclsh after the script filename are stored as a list in the global Tcl variable, argv (and the length of that list is put in argc; you don't need that because Tcl lists know their own length). This means that you can then use normal list processing commands such as lindex, lassign or foreach to access the values in that list:

set filename [lindex $argv 0]
puts "The filename is \"$filename\""

set f [open $filename]
set line [read $f]
puts "The first line of \"$filename\" is \"$line\""
Sign up to request clarification or add additional context in comments.

Comments

4

Call the script with tclsh myscript.tcl myfile.txt and in the script:

lassign $argv filename
set fid [open $filename]

If you want to pass several filenames: tclsh myscript.tcl file1 file2 file3

foreach filename $argv {
    puts "Operating on: $filename"
    set fid [open $filename]
    # ...
}

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.