当前位置: 动力学知识库 > 问答 > 编程问答 >

different uses of Call in a batch file

问题描述:

I was assigned to understand the code that was written by some other person so far I could understood to some extent but one line is causing me trouble

call set mmm=%%mon:~%id%,3%%

To the extent I understand call is used to initiate another batch file but in the above line there was variable set to some value but I am not sure what does that line does.

Also how does %% is used here as far as I know % is used to retrive the value from a variable.

Please help me in understanding. Complete code is here.

set mon=JANFEB

set id=123

call set mmm=%%mon:~%id%,3%%

Thanks for your time.

网友答案:

It's a two-stage substitution, allowing you to use variables within the interpretation. Normally, with an expression like:

%str:~start,len%

the start and len must be numeric constants rather than variables. So this is the way you use a variable instead of a constant.

Starting with:

set mmm=%%mon:~%id%,3%%

In the first stage, %% markers are replaced with % and %id% is replaced with 123, giving:

set mmm=%mon:~123,3%

In the second stage, it's interpreted as you would expect, although the offset 123 seems a little strange in this case.

You can see the effect here:

@setlocal enableextensions enabledelayedexpansion
@echo off

rem               1         2         3         4
rem     01234567890123456789012345678901234567890123456
set mon=JAN.FEB.MAR.APR.MAY.JUN.JUL.AUG.SEP.OCT.NOV.DEC
rem                                 ^
rem                                28

set id=28
call set mmm=%%mon:~%id%,3%%
echo %mmm%

endlocal

which outputs AUG.

网友答案:

Two steps:

first, the value of id is substituted into the expression, so it becomes set mmm=%%mon:~123,3%%

Then the expression is evaluated - as a single-line "subroutine", removing one level of % : set mmm=%mon:~123,3%

so, attempts to set mmm to the 3 characters following the 1323rd character in mon (counting from "character 0")

Which should "set" mon to nothing

(if id was 3, then mmm would be set to Feb)

分享给朋友:
您可能感兴趣的文章:
随机阅读: