#!/usr/bin/env perl
our
(
$mydir
,
$myname
);
BEGIN {
my
$location
= (-l $0) ? abs_path($0) : $0;
$location
=~ /(.*?)([^\/]+?)_?\z/s or
die
"?"
;
(
$mydir
,
$myname
) = ($1, $2);
}
sub
usage {
print
"usage:
$myname
[-o xmlfile] csvfile(s)
Open and
read
csvfile containing CSV
with
4 columns, and
write
it to
xmlfile or stdout as XML. Does streaming, i.e. only loads one row
(plus some buffering) into memory at a
time
.
";
exit
(
@_
? 1 : 0);
}
our
$verbose
= 0;
our
$outpath
;
GetOptions(
"verbose"
=> \
$verbose
,
"help"
=>
sub
{usage},
"outpath=s"
=> \
$outpath
,
) or
exit
1;
usage
unless
@ARGV
;
qw(myexample
protocol-version
records
record
a
b
c
d)
;
sub
print_csv_as_xml {
my
(
$fh
,
$path
) =
@_
;
my
$rows
= csv_file_to_rows
$path
, +{
eol
=>
"\n"
,
sep_char
=>
";"
};
$rows
= rest
$rows
;
my
$xmlstream
= MYEXAMPLE(
PROTOCOL_VERSION(
"0.123"
),
RECORDS
(
$rows
->
map
(
sub
{
my
(
$row
) =
@_
;
@$row
== 4 or
die
"row doesn't contain 4 columns: @$row"
;
my
(
$a
,
$b
,
$c
,
$d
) =
@$row
;
RECORD(A(
$a
), B(
$b
), C(
$c
), D(
$d
))
}
)
)
);
pxml_print
$xmlstream
,
$fh
;
}
my
$fh
=
defined
$outpath
? xtmpfile
$outpath
: glob_to_fh * STDOUT;
print_csv_as_xml
$fh
,
$_
for
@ARGV
;
$fh
->xclose;
$fh
->xputback(0666 & ~
umask
)
if
defined
$outpath
;