Page 1 of 1

how to preserve leading spaces in parameter during function call

Posted: 14 Apr 2019 14:54
by sincos2007

Code: Select all

@echo off

set str="   1234567"
call :func1 %str%

echo Press any key to exit...
pause>NUL
goto :eof

:func1
setlocal EnableDelayedExpansion

set "str=%~1"
echo func1: {%str%}

call :func2 %str%

endlocal
goto :eof


:func2
setlocal EnableDelayedExpansion

set "str=%1"
echo func2: {%str%}

endlocal
goto :eof
by my observation, parameter passed to func1 preserves the leading spaces but func2 not.

How to preserve leading spaces during function calls?

Thanks

Re: how to preserve leading spaces in parameter during function call

Posted: 14 Apr 2019 15:39
by aGerman
Spaces are separators for command line arguments (not only on Windows btw). Say you have a string like that:

Code: Select all

   a   b c   
(note there are spaces behind c, too)
If you pass that string in a command line then leading and trailing spaces are discarded, multiple spaces in between are treated as one and are used to separate a, b, and c. So, for this example you receive 3 arguments that consist of a single character each. In order to preserve the spaces you have to enclose the string into quotation marks as you did in your main code. You may remove them later on using %~1 instead of %1.

Steffen

Re: how to preserve leading spaces in parameter during function call

Posted: 15 Apr 2019 01:18
by jeb
There are two fundamental differnt ways to handle function parameters
1) Use a parameter ByValue, like you do in CALL :myFunc %str%
This technic is simple but has also some limitations with special characters like quotes, spaces and carets.
You should at least quote the content to presever spaces and avoid problems with &|<> characters, but as said, it can't be used in any situation

Code: Select all

call :strlen "  a   b   c  "
...
:strLen
set "content=%~1"
...

2) Use a parameter ByReference, only the name of the variable is used, not the content itself, ex. CALL :myFunc str1
The advantage is, that the content won't be modified by the CALL and it's possible to handle any content.
set "str=This is a caret ^ and & other "Hard ^& special" content"

call :strLen str
...

:strLen
set "content=!%1!"
..

Re: how to preserve leading spaces in parameter during function call

Posted: 15 Apr 2019 10:55
by sincos2007
Hi Steffen,

I see.

thanks for your help.

Re: how to preserve leading spaces in parameter during function call

Posted: 15 Apr 2019 10:56
by sincos2007
Hi jeb,

Your code works fine.

thanks a lot