Comments these days:

PS I:> Add-Thought "Success is journey, not destination."

Monday, February 13, 2012

Loading file content into Array of Hash Table

While programming, sometimes we need to read some configuration entries from a flat file. There are several approaches to do it, I have followed the below approach to read file-entries into a hash table which is also an array.
I have assumed that there is a flat file which contains multiple lines of information about employee. This can be configuration settings or it can be anything. I have used this simple example for simplicity -
clear
#---------------------------------------------------------------------------------------------#
#
--Script to load file into an Array of Hash Table
#
---------------------------------------------------------------------------------------------#

#--[1]- Let's create a file with entries seperated by comma --#
$file_name="D:\Check\file.txt"
echo "1,John,5000" > $file_name echo "2,Jack,3000" >> $file_name
echo "3,Jack,3000" >> $file_name

#--[2]- Load the information into an Hash table Array --#

$emp_data = @()
$file_entries = gc $file_name
foreach ( $file_entry in $file_entries )
{
$emp_id=$file_entry.split(",")[0]
$emp_name=$file_entry.split(",")[1]
$emp_salary=$file_entry.split(",")[2]

$emp_data += @{emp_id="${emp_id}"; emp_name="$emp_name"; emp_salary="${emp_salary}"}
}
#--[3]- Display the same --#
for ($x=0 ; $x -lt $emp_data.Count ; $x++)
{

$emp_data[$x].emp_id
$emp_data[$x].emp_name
$emp_data[$x].emp_salary

}
#---------------------------------------------------------------------------------------------#
#
End of Code
#
---------------------------------------------------------------------------------------------#



There might be many other approach to do it, I do not advocate it as a best approach, but if you want to have full control and understandability of the code, you may use the above approach.

No comments:

Post a Comment