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.
2 Answers
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\""