Batch Script – Creating Structures in Arrays
In this article, we’ll understand how to create structures in arrays in a batch script.
What are Structures?
Structures are like a multi-type list of values, unlike arrays we have a list of single type values. Let’s say we have an array called person, we have initially declared to a list of names, but if we want to add age, phone number, or gender, we need to create separate arrays to contain them and carefully index them as per the name in the initial array. By creating structures in arrays, we can create multiple lists like structures in a single array.
How to create Structures using Arrays?
To create a structure in an array, we need to create the list similarly but by adding the dot [.] operator along with the identifier to each of the elements.
We can define easily define structures in an array by defining the index prefixed with the name of the component with a dot operator.
Let’s take an example of a structure of a person, we can have components/keys like name, age, gender, etc. We can create the array elements and their keys one by one.
@echo off set struct.name=John set struct.age=12 set struct.gender="M" set struct.name=Kevin set struct.age=20 set struct.gender="M" set struct.name=Jessie set struct.age=15 set struct.gender="F" FOR /L %%i IN (0 1 2) DO ( call echo Name: %%struct[%%i].name%%, Age:^ %%struct[%%i].age%%, Gender:, %%struct[%%i].^ gender%% )
So from the above code, we can see that we have created a structure from a single array. We have different types of variables like string, integer, and character. These structures in the form of arrays can be retrieved by dot prefixing the name of the components in the structure with the list. That is in this example, we have used %%struct[%%i].name%% for accessing the name of the ith element in the array struct, the .name%% is the identifier for the name component in the structure.
We can extend this further to create customized structures with multiple types and components in a form of a list. This is how we can create structures in BAtch scripts.