user3093536
user3093536

Reputation: 95

Setting Variables in Variables in Batch

I'm trying to efficiently name variables a1 through a9 with !%f%! through !%q%!. I tried creating a for loop to complete this:

set w=0
for %%K in (f g h i k l m o q) do (
    set /a w+=1
    set /a b%w%=%!%%K!%
    set /a a%w%=!b%w%!%%13
)

The error is that there is a missing operator, so I'm assuming that the parenthesis and exclamation marks are being misread. How would I go about fixing this problem?

TL;DR

Make:

set /a a1=!%f%!%%13
...
set /a a9=!%q%!%%13

...more efficient.

To clarify, %f% is equal to say 4D and %4D% is equal to 9.

I need the modulus of 9 and 13 as the a1.

Upvotes: 1

Views: 86

Answers (2)

dbenham
dbenham

Reputation: 130809

I believe at least one problem you are facing, based on your comment below your question, is that a variable name of 4D will be interpreted by SET /A as the number 4 followed by variable D, which would be invalid.

Another issue you have is that the expansion of %w% will be a constant value within the loop. You need delayed expansion !w! instead.

I believe this is what you want.

set w=0
for %%K in (f g h i k l m o q) do (
  set /a w+=1
  for %%V in (!%%K!) do set /a a!w!=!%%V!%%13
)

If none of your variable names begin with a number, then you could simply use

set w=0
for %%K in (f g h i k l m o q) do (
  set /a w+=1
  set /a a!w!=!%%K!%%13
)

I try to avoid using a number as the leading character for a variable name for two reasons:

1) SET /A will not expand the variable properly, as you are experiencing in your question.

2) Normal expansion of %4D% would be interpreted as value of argument %4, followed by D, followed by a % that would be stripped from the result.

Upvotes: 2

unclemeat
unclemeat

Reputation: 5197

setLocal enableDelayedExpansion
set w=0
for %%K in (f g h i k l m o q) do (
    set /a w+=1
    set a!w!=^^!%%%%K%%^^!%%%%13
)

:: as a test
echo !a5!

This should do the trick for you. Carat ^ is the batch escape character.

Upvotes: 0

Related Questions