1

I was curious why the variable in my list doesn't expand when I perform a foreach loop...

set DIR_FILES "./files"

# HDL Library Files lists
set file_list {
   "$DIR_FILES/aa.txt" \
   "$DIR_FILES/bb.txt" \
   "$DIR_FILES/cc.txt" \
}

foreach library $file_list {
    puts ">>> ($library)";
}

Output is this:

>>> (./files/aa.txt)
>>> (./files/bb.txt)
>>> (./files/cc.txt)

Instead of this:

Output is this:

>>> ($DIR_FILES/aa.txt)
>>> ($DIR_FILES/bb.txt)
>>> ($DIR_FILES/cc.txt)

2 Answers 2

2

I was curious why the variable in my list doesn't expand when I perform a foreach loop...

This is because the use of curly braces prevents variable substitution from happening (see Tcl doc):

Variable substitution is not performed on words enclosed in braces.

You might consider the following alternatives:

set file_list [list \
   $DIR_FILES/aa.txt \
   $DIR_FILES/bb.txt \
   $DIR_FILES/cc.txt
]

to create a Tcl list directly, rather than a string in list format.

or

set file_list [subst -nocommands -nobackslashes {
   $DIR_FILES/aa.txt
   $DIR_FILES/bb.txt
   $DIR_FILES/cc.txt
 }]

to spare the backslashes to cover for multi-line formatting.

Sign up to request clarification or add additional context in comments.

1 Comment

Be cautious with the subst option. It has the same problem as enclosing the list in quotes when DIR_FILES contains a space. My advise would be to go for the solution that uses the list command.
-1
set DIR_FILES "./files"

# HDL Library Files lists
set file_list " \
   $DIR_FILES/aa.txt \
   $DIR_FILES/bb.txt \
   $DIR_FILES/cc.txt \
"

foreach library $file_list {
    puts ">>> ($library)";
}

2 Comments

Because this is so close to the original code, it would be useful to provide an explanation of the difference—namely in terms of how you're closing the list. That will make it easier for the OP and future commentors to quickly parse what's going on. Can you edit your question to provide an explanation?
This will not produce the desired result if DIR_FILES contains a space. That's why it is usually better to use list commands to produce a list.

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.