How to convert hash table to CSV file on Perl? -
i beginner using perl scripting. right have hash table store on variable ($xml
) don't know how convert csv file. here content of hash table.
$var1 = { 'result' => { 'item' => [ { 'bootbox8_id' => '222333', 'site_id' => '144', 'key' => '0', 'os_version' => '3.1', 'switch_name' => 'switch1.name.com', 'type_id' => '109', 'mac' => { 'item' => { 'content' => '00:b0:92:2c:cb:9d', 'key' => '0' } }, 'property' => 'sales', 'console' => 'console.name.com', 'name' => 'india2.name.com', 'bootbox8' => 'console.name.com', 'os_name' => 'linux', 'site' => 'india', 'manufacturer' => 'xxx', 'model' => 'xxx-4', 'id' => '1083376', }, { 'bootbox2_id' => '222333', 'site_id' => '144', 'key' => '1', 'os_version' => '3.1', 'switch_name' => '', 'type_id' => '109', 'mac' => { 'item' => { 'content' => '00:b0:98:1b:c6:e2', 'key' => '0' } }, 'property' => 'sales', 'console' => 'console.name.com', 'name' => 'india1.name.com', 'bootbox2' => 'console.name.com', 'os_name' => 'linux', 'site' => 'india', 'manufacturer' => 'xxx', 'model' => 'xxx-4', 'id' => '1083377', } ] }, 'meta' => { 'total_pages' => '1', 'current_page' => '1', 'per_page' => '10', 'total' => '2' } };
and collect fields on hash table , convert csv file below.
india2.name.com,sales,india,linux,xxx-4 india1.name.com,sales,india,linux,xxx-5
could provide detail sample can learn on that?
you need iterate on data. actual items in $xml->{result}->{item}
. need dereference using @{ }
. each item simple hashref. can join
data using keys want.
foreach $item ( @{$xml->{result}->{item}} ){ join ',', $item->{name}, $item->{property}, $item->{site}, $item->{os_name}, $item->{model}; }
if want little shorter, use hashref slice.
foreach $item ( @{$xml->{result}->{item}} ){ join ',', @{$item}{qw(name property site os_name model)}; }
i'm asuming know how open
file writing. if want more complex stuff csv, use text::csv excelent csv handler take lot of pain away.
check out perlreftut more infos on how work references.
Comments
Post a Comment