1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How to access array elements?

Discussion in 'Support' started by Steve Fabian, Oct 21, 2010.

  1. Steve Fabian

    Joined:
    May 20, 2008
    Messages:
    3,523
    Likes Received:
    4
    What is the syntax by which commands in a batch file can access the elements
    of an array when the name of the array is the first of the calling
    parameters of the batch file?

    Example:

    --- file caller.btm ---
    setarray myarray[1,2,3,4]
    call xyz.btm myarray
    --- end of file caller.btm ---

    --- file xyz.btm ---
    echo array %1
    for /l %n in (0,1,5) echo %n %@arrayinfo[%1,%n]
    switch %@arrayinfo[%1,0]
    case 1
    echo %1[0]
    case 2
    echo %1[0,0]
    case 3
    echo %1[0,0,0]
    case 4
    echo %1[0,0,0,0]
    endswitch
    quit
    --- end of file xyz.btm ---

    In the above example, I also tried %[1[0]] and %[%1[0]] in lieu of %1[0].

    Note: I came across this problem when I tried to write a batch file to
    perform the reverse of the function @filearray, i.e., to write the contents
    of an array to a file.
    --
    Steve
     
  2. Charles Dye

    Charles Dye Super Moderator
    Staff Member

    Joined:
    May 20, 2008
    Messages:
    3,280
    Likes Received:
    38
    Borrowing a clever trick someone posted recently:

    Code:
    @echo off
    echo array %1
    for /l %n in (0,1,5) echo %n %@arrayinfo[%1,%n]
    echo.
    echo Dump first element:
    switch %@arrayinfo[%1,0]
    case 1
    echo %@execstr[set %1[0]]
    case 2
    echo %@execstr[set %1[0,0]]
    case 3
    echo %@execstr[set %1[0,0,0]]
    case 4
    echo %@execstr[set %1[0,0,0,0]]
    endswitch
    quit
    
     
  3. samintz

    samintz Scott Mintz

    Joined:
    May 20, 2008
    Messages:
    1,178
    Likes Received:
    11
    Surprisingly, this does *not* work either:

    set arr=%1[0]
    echo %arr %[%arr]

    -Scott


    Charles Dye <> wrote on 10/21/2010 12:20:30 PM:


    elements

     

Share This Page