You are not logged in.

#1 21 Nov 2020 10:33

Rekrul
Member
Registered: 17 Apr 2016
Posts: 98

FOR tokens don't survive calling a subroutine?

I'm been reading the pages on For, and Call and I can't figure why this doesn't work;

@echo off
for %%f in (*.*) do call :Display

goto End

:Display
echo %%f
exit /b

:End

Variables survive the Call intact, but tokens don't? What arcane rule have I violated now?

Offline

#2 21 Nov 2020 18:31

OJBakker
Member
Registered: 05 Aug 2011
Posts: 6

Re: FOR tokens don't survive calling a subroutine?

Your Display subroutine is outside of the scope of the for-loop.
The for-parameter is usually only available inside it's command block.
The for-parameter is special in the sense that it is a sort of global parameter, but only within the scope of a for-loop, but this can also be a different for-loop!.

Solution 1: use the value of the for-parameter as explicit parameter to the Display routine.

@echo off
for %%f in (*.*) do call :Display "%%f"

goto End

:Display
echo %~1
exit /b

:End

Solution 2: use a for-loop in the Display subroutine.

@echo off
for %%f in (*.*) do call :Display

goto End

:Display
for %%. in (.) do echo %%f
exit /b

:End

:End

Offline

#3 23 Nov 2020 10:24

bluesxman
Member
From: UK
Registered: 29 Dec 2006
Posts: 1,129

Re: FOR tokens don't survive calling a subroutine?

Rekrul wrote:

Variables survive the Call intact, but tokens don't? What arcane rule have I violated now?

Correct.  I'd imagine it's because it's not actually a variable and thus only exists in the confines of the `for` loop.  When you do a `call` it's actually starting another another shell, and only variables are inherited by sub shells.

As mentioned elsewhere, passing it as a parameter is one way to handle this, setting a variable would be another (but it really depends on your use case).

Last edited by bluesxman (23 Nov 2020 10:26)


cmd | *sh | ruby | chef

Offline

Board footer

Powered by