#!/usr/bin/env perl use strict; use warnings; use autodie qw{:all}; use Text::CSV; use XML::LibXML; my $tsv_file_in = 'pm_1169537_input.tsv'; my $xml_file_out = 'pm_1169537_output.xml'; my $dom = generate_xml($tsv_file_in); output_xml($dom, $xml_file_out); sub generate_xml { my ($tsv_file_in) = @_; open my $in_fh, '<', $tsv_file_in; my $csv = Text::CSV::->new({sep_char => "\t"}) or die 'Text::CSV::->new() FAILED: ', Text::CSV::->error_diag(); my $dom = XML::LibXML::Document::->new(qw{1.0 UTF-8}); my $root = $dom->createElement('XML_FILE'); $dom->setDocumentElement($root); my @headers = map { uc } @{$csv->getline($in_fh)}; my %header_index_for = map { $headers[$_] => $_ } 0 .. $#headers; my ($last_pin, $report) = ('', undef); while (my $row = $csv->getline($in_fh)) { next if @$row == 1 && ! length $row->[0]; if ($row->[$header_index_for{PIN}] ne $last_pin) { $last_pin = $row->[$header_index_for{PIN}]; $report = XML::LibXML::Element->new('REPORT'); $report->setAttribute(TYPE => 'AB'); $root->addChild($report); for (qw{REASON1 REASON2 REASON3}) { my $reason = XML::LibXML::Element->new($_); $reason->appendText($row->[$header_index_for{$_}]); $report->addChild($reason); } my $person = XML::LibXML::Element->new('PERSON'); $report->addChild($person); for (qw{PIN NAME ZIP}) { my $person_datum = XML::LibXML::Element->new($_); $person_datum->appendText($row->[$header_index_for{$_}]); $person->addChild($person_datum); } } my $charge = XML::LibXML::Element->new('CHARGE'); $report->addChild($charge); for (qw{DATE TIME}) { my $charge_datum = XML::LibXML::Element->new($_); $charge_datum->appendText($row->[$header_index_for{$_}]); $charge->addChild($charge_datum); } } return $dom; } sub output_xml { my ($dom, $xml_file_out) = @_; open my $out_fh, '>', $xml_file_out; print $out_fh $dom->toString(1); return; } #### data1 data2 data3 Pin 1 data5 data6 data7 data9 data11