LoginSignup
0
0

More than 3 years have passed since last update.

Windows batで疑似関数

Last updated at Posted at 2019-12-31

概要

batで関数を擬似的に扱うためのもの
備忘録程度に記載

基本形

:func
  setlocal
  @rem なにか関数化したい処理
  endlocal
exit /b

※setlocal,endlocalは必要に応じて記載

使い方

main.bat
@echo off
call :hello
exit

:hello
  setlocal
  echo hello
  endlocal
exit /b
output
hello

発展1 引数ありの場合

argument.bat
@echo off
call :argument hello world
exit

:argument
  setlocal
  echo %1 %2
  endlocal
exit /b
output
hello world

発展2 返り値が固定量の場合(not errorlevel)

return.bat
@echo off
call :return
echo %ret%
exit

:return
  setlocal
  set ret=hello
  endlocal&set ret=%ret%
exit /b
output
hello

※返り値を増やしたい場合はendlocal部に&set 返り値名=%返り値名%を継ぎ足す

発展3 返り値が不定量の場合(not errorlevel)

returnval.bat
@echo off
call :returnval hello world
echo %ret[0]% %ret[1]%
pause
exit

:returnval
  @rem 遅延展開の有効化
  setlocal enabledelayedexpansion
  @rem 初期化
  set cnt=0
  set tmpdata=
  set LF=^


  @rem 返したいデータの集約
  :returnval_re1 
    set tmpdata=%tmpdata%%cnt%,%1;
    shift
  if not "%1"=="" set /a cnt+=1&goto returnval_re1
  @rem 値を返す
  set tmpdata=%tmpdata:;=!LF!%
  for /f "tokens=1,2 delims=," %%i in ("!tmpdata!") do endlocal&set ret[%%i]=%%j
exit /b
output
hello world

※コマンドプロンプトの仕様上1行に入力できる文字数が8190文字までのためtmpdataには最大8121文字までしか入らない
 それ以上返したい場合はデータの圧縮やファイル書き出しなどの対策が必要

参考

setlocal~endlocalの外に変数をたくさん持ち出す

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0