in reply to How do I access values in a hash by two different keys?
G'day Dimitri,
The fact that accessing $config->{item} with a hash key worked (i.e. $config->{item}{"bla"}), while accessing it with an array index gave an error (i.e. $config->{item}[$i]), should have provided a huge clue as to what was going on. Regardless, in situations where you are encountering these sorts of difficulties, it's quite useful to look at the data structure that XML::Simple is generating (e.g. with Data::Dumper):
$ perl -Mstrict -Mwarnings -E ' use Data::Dumper; use XML::Simple qw{:strict}; my $xml = <<EOX; <?xml version="1.0" encoding="UTF-8"?> <config> <item> <id>0</id> <filename>AMEX</filename> <destination_dir>test</destination_dir> </item> <item> <id>1</id> <filename>bla</filename> <destination_dir>test1</destination_dir> </item> <item> <id>2</id> <filename>alb</filename> <destination_dir>test2</destination_dir> </item> </config> EOX my $config = XMLin($xml => KeyAttr => {item=>"filename"}, ForceArr +ay => ["item"]); print Dumper $config; ' $VAR1 = { 'item' => { 'alb' => { 'id' => '2', 'destination_dir' => 'test2' }, 'AMEX' => { 'destination_dir' => 'test', 'id' => '0' }, 'bla' => { 'id' => '1', 'destination_dir' => 'test1' } } };
Armed with that information, it should now be easy to extract the data you want:
$ perl -Mstrict -Mwarnings -E ' use XML::Simple qw{:strict}; my $xml = <<EOX; <?xml version="1.0" encoding="UTF-8"?> <config> <item> <id>0</id> <filename>AMEX</filename> <destination_dir>test</destination_dir> </item> <item> <id>1</id> <filename>bla</filename> <destination_dir>test1</destination_dir> </item> <item> <id>2</id> <filename>alb</filename> <destination_dir>test2</destination_dir> </item> </config> EOX my $config = XMLin($xml => KeyAttr => {item=>"filename"}, ForceArr +ay => ["item"]); say "*** bla destination ***"; say $config->{item}{bla}{destination_dir}; say "*** all destinations ***"; for (keys %{$config->{item}}) { say "$_: ", $config->{item}{$_}{destination_dir}; } ' *** bla destination *** test1 *** all destinations *** alb: test2 AMEX: test bla: test1
If you need to change the options to XMLin, continue to use Data::Dumper (or your preferred equivalent) to see the effects of those option changes.
-- Ken
|
|---|