perl - How Can I Remove Magic Number when using XML::Simple? -
i did exercise this, how calculate # of xml elements collapsed array xml::simple don't have hard-code # of elements? plan use code parse bigger xml file. don't want cout elements manual.
can use count replace magic numbers, little person.count
or hobbie.length
etc. know, can use kind of statement in c# conveniently.
#!/usr/bin/perl -w use strict; use xml::simple; use data::dumper; $tree = xmlin('./t1.xml'); print dumper($tree); print "\n"; (my $i = 0; $i < 2; $i++) # magic number '2' { print "$tree->{person}->[$i]->{first_name} $tree->{person}->[$i]->{last_name}\n"; print "\n"; (my $j = 0; $j < 3; $j++) # magic number '3' { print $tree->{person}->[$i]->{hobbie}->[$j], "\n"; } print "\n"; }
out put:
could not find parserdetails.ini in c:/perl/site/lib/xml/sax $var1 = { 'person' => [ { 'hobbie' => [ 'bungy jumping', 'sky diving', 'knitting' ], 'last_name' => 'bloggs', 'first_name' => 'joe' }, { 'hobbie' => [ 'swim', 'bike', 'run' ], 'last_name' => 'liu', 'first_name' => 'jack' } ] }; joe bloggs bungy jumping sky diving knitting jack liu swim bike run
my xml source file below
<document> <person> <first_name>joe</first_name> <last_name>bloggs</last_name> <hobbie>bungy jumping</hobbie> <hobbie>sky diving</hobbie> <hobbie>knitting</hobbie> </person> <person> <first_name>jack</first_name> <last_name>liu</last_name> <hobbie>swim</hobbie> <hobbie>bike</hobbie> <hobbie>run</hobbie> </person> </document>
since xml::simple produce array you, it's easy count length.
e.g. $tree->{person}
array - or rather array reference (make sure it's 1 using forcearray option of xml::simple if there's 1 person).
you can length first de-referencing array (using
@{}
array de-reference):@{ $tree->{person} }
then use resulting array in scalar context evaluates # of elements in array (in other words,
a.lenth
/a.count
functions in other languages translate perl idiomscalar(@a)
scalar()
function optional if scalar context applies).in case, numeric comparison operator
"<"
force scalar context, if not case have usedscalar()
function.
example:
# don't forget forcearray option of xml::simple ensure person , hobbie array refs (my $i = 0; $i < scalar( @{ $tree->{person} } ); $i++) { # scalar() optional here print "$tree->{person}->[$i]->{first_name} $tree->{person}->[$i]->{last_name}\n"; print "\n"; (my $j = 0; $j < @{ $tree->{person}->[$i]->{hobbie} }; $j++) { print $tree->{person}->[$i]->{hobbie}->[$j], "\n"; } print "\n"; }
as note, different method of counting length of perl array $#a
construct, returns the index of last element of array - e.g. 1 less amount of elements in array. i'm not aware of performance difference between using 2 approaches, if find both equally readable, use them appropriate (e.g. if need index of last element, use $#a
; if # of elements, use @a
or scalar(@a)
needed).
a reference perl data structures cookbook @perldoc
Comments
Post a Comment