#!/usr/bin/perl
use strict;
use warnings;
#use Text::CSV_XS;
my $csv = CSV_Stub->new();
my $file = '';
if (defined $ARGV[0]) {
$file = $ARGV[0];
}
open(my $data, '<', $file) or die "Could not open '$file'\n";
# Get raw textual input: an array of strings
my @input = <$data>;
close $data;
# Convert CSV text into an array of arrays
@input = map { $csv->parse($_); [$csv->fields()] } @input;
# Use input data to build a data structure which maps (fairly closely) onto what we want to output
# A hash of arrays
# Key = order id
# Value = the array of items in that order
my %internalRepresentation;
foreach my $input (@input)
{
push @{$internalRepresentation{$input->[0]}}, {
name => $input->[1],
itemId => $input->[2],
itemDesc => $input->[3],
price => $input->[4],
}
}
# For each order we want to output:
foreach my $orderNumber (keys %internalRepresentation)
{
open (OUTFILE, "> output/$orderNumber.xml") or die $! . " can't open the file\n";
print OUTFILE "\n";
print OUTFILE " $orderNumber\n";
print OUTFILE " $internalRepresentation{$orderNumber}->[0]->{name}\n";
# For each item in the order:
foreach my $item (@{$internalRepresentation{$orderNumber}})
{
print OUTFILE " - \n";
print OUTFILE " $item->{itemId}\n";
print OUTFILE " $item->{itemDesc}\n";
print OUTFILE " $item->{price}\n";
print OUTFILE "
\n";
}
print OUTFILE "\n";
close OUTFILE;
}
package CSV_Stub;
sub new
{
return bless {}, shift;
}
sub parse
{
my $self = shift;
my $line = shift;
chomp $line;
$self->{currentFields} = [split ",", $line];
return 1;
}
sub fields
{
my $self = shift;
return @{$self->{currentFields}};
}
####
->[0]