creating multidimension array with multiple coloumn in perl -
id cat 1 car 2 education 3 mathematics 4 physics 5 astrophysics
based on list, want generate , access array in following manner:
array ( [0] => array ( [id] => 1 [cat] => car ) [1] => array ( [id] => 2 [cat] => education ) [2] => array ( [id] => 3 [cat] => mathematics ) )
and on till end of array.
a simple way read file, line-by-line, split each line id , category portions , use create array of hash references:
use strict; use warnings; use data::dumper; @categories; while ( $row = <data> ) { ($id, $cat) = $row =~ m/(\d+)\s+(\w+)/; push @categories, { id => $id, cat => $cat }; } print dumper \@categories; __data__ 1 car 2 education 3 mathematics 4 physics 5 astrophysics
output:
$var1 = [ { 'cat' => 'car', 'id' => '1' }, { 'cat' => 'education', 'id' => '2' }, { 'cat' => 'mathematics', 'id' => '3' }, { 'cat' => 'physics', 'id' => '4' }, { 'cat' => 'astrophysics', 'id' => '5' } ];
if file anymore complex (e.g. has quoting) should use text::csv_xs
Comments
Post a Comment