I am trying to alter some XML to group events by time, by moving the time tag from within the event to within its parent. That is...
<schedule>
<event>
<time>02:00</time>
<other_details>details</other_details>
</event>
<event>
<time>02:00</time>
<other_details>details</other_details>
</event>
<event>
<time>03:00</time>
<other_details>details</other_details>
</event>
<schedule>
should become
<schedule>
<event>
<time>02:00</time>
<event_details>
<other_details>details</other_details>
</event_details>
<event_details>
<other_details>details</other_details>
</event_details>
</event>
<event>
<time>03:00</time>
<event_details>
<other_details>details</other_details>
</event_details>
</event>
</schedule>
The way I've approached this is using XML::Simple to read the XML into a hash, taking the time out, and using it as a key for another hash which holds an array of event_details
. Code:
#!/Perl/bin/perl
#scheduleConversion.plx v1.0
use strict;
use warnings;
use XML::Simple;
use Data::Dumper;
use constant EVENTTAG => 'event';
use constant TIMETAG => 'event_time';
use constant DETAILSTAG => 'event_details';
if($#ARGV != 0) {
print "Usage: First argument should be filename, optionally with path.";
}
# Get filename/path from the arguments
my $docname = shift @ARGV;
# Create a new XML parser
my $xml = new XML::Simple;
# Read in the XML data
my $XMLdata = $xml->XMLin($docname);
# New XML data to be output
my %XMLnew;
$XMLnew{&EVENTTAG} = [];
my %timeGroups;
foreach (@{$XMLdata->{&EVENTTAG}}) {
my $time = ${$_}{&TIMETAG};
delete ${$_}{&TIMETAG};
# Make an array if none exists
$timeGroups{$time} = [] unless exists($timeGroups{$time});
# Add our details to the array
push($timeGroups{$time}, $_);
}
foreach (%timeGroups) {
push ($XMLnew{&EVENTTAG}, $_{&EVENTTAG});
}
#print $xml->XMLout(%XMLnew);
The issue is when I try to print Dumper(%timeGroups);
, it gives me a result like this:
$VAR1 = '2015-09-10 03:59:00';
$VAR2 = [
{
'event_detail_1' => 'details_1',
'event_detail_2' => 'details_2'
}
];
I would expect to see the date as the key, but it seems to be a different entry entirely. I tested this with a separate hash, also creating a key/value pair as $hash{key} = 'value'
, which gave the same unexpected result as above, while $hash = {'key' => 'value'}
gave the expected result.
I'm sure I'm just missing something about how Perl hashes work, but it was my understanding both of these methods should be equivalent. I've smacked the problem with my brain all day and I've just managed to narrow it down to this cause.