Please don't use regexes to parse XML.
#!/usr/bin/env perl
use warnings;
use strict;
use XML::LibXML;
my $doc = XML::LibXML->load_xml( location => 'in.xml' );
my (@data, %maxlen);
for my $food ( $doc->findnodes('/breakfast_menu/food') ) {
my %elem;
for my $t ( qw/ name price / ) {
# assume only one of these elements each per <food>
my ($str) = $food->getElementsByTagName($t);
$str = $str->textContent;
$str =~ s/^\s*\$// if $t eq 'price';
if ( !defined $maxlen{$t} || length $str > $maxlen{$t} )
{ $maxlen{$t} = length $str }
$elem{$t} = $str;
}
push @data, \%elem;
}
@data = sort { $a->{name} cmp $b->{name} } @data;
for my $elem (@data) {
printf "%-$maxlen{name}s %$maxlen{price}.2f\n",
$elem->{name}, $elem->{price};
}
__END__
Belgian Waffles 5.95
Berry-Berry Belgian Waffles 8.95
French Toast 4.50
Homestyle Breakfast 6.95
Strawberry Belgian Waffles 7.95
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|