Comments these days:

Simplicity of a person is always remembered. Don't forget, this is only left once you leave this world...

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 -
--Script to load file into an Array of Hash Table

#--[1]- Let's create a file with entries seperated by comma --#
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_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++)


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