I wanted to build an awesome place for people to discuss module specific issues, but I don't have any more time for this, and there are much better places to discuss Perl-related issues. I'd recommend asking your question on Stack Overflow or on Perl Monks.
If you are looking for a Perl tutorial or Perl-related news, I hope these links will serve you well.
Posted on 2007-11-21 22:17:56-08 by grantm in response to 6493
Re: XML::Simple Sorting

The simplest answer is "don't do that". If you want elements output in a particular order then they should be in an arrayref in your data structure rather than a hashref, e.g.:

my $hashref = { item => [ { id => 1, label => 'foo' }, { id => 2, label => 'bar' }, { id => 11, label => 'baz' }, ] };

Another approach would be leave your data structure as it is but override XML::Simple's 'hash_to_array' method, e.g.:

#!/usr/bin/perl use strict; use warnings; my $hashref = { item => { "2" => { label => 'bar' }, "1" => { label => 'foo' }, "11" => { label => 'baz' } } }; my $xs = XML::SortedSimple->new(); my $xml = $xs->XMLout( $hashref, KeyAttr => ['id'] ); print $xml; package XML::SortedSimple; use base 'XML::Simple'; sub hash_to_array { my $self = shift; my $ref = $self->SUPER::hash_to_array(@_); if( UNIVERSAL::isa($ref, 'ARRAY') ) { $ref = [ sort { $a->{id} || 0 <=> $b->{id} || 0 } @$ref ]; } return $ref; }

In this example, any hashref that does get unfolded into an arrayref will have its elements sorted (numerically) by the value of the id keys. Probably best to go with massaging your data structure though.

Direct Responses: 6495 | Write a response