Thread

Posted on Wed Aug 30 01:43:28 2006 by ryan
Can't use string as HASH ref
Can you please show me how to iterate through my staff members without getting the error seen below +. In my example, iterating multiple animals works fine, but iterating a single staff member errors. #!/usr/bin/perl use strict; use Data::Dumper; use XML::Simple; &create_zoo; &display_zoo; sub create_zoo{ my %zoo=( animals=>{ 1=>{type=>'tiger', nickname=>'tom'} ,2=>{type=>'lion', nickname=>'leo'} } ,staff=>{ 1=>{role=>'manager', nickname=>'mike'} } ); print "------------------\n"; print "Data Dump\n"; print Dumper(\%zoo); print "------------------\n"; my $xml = new XML::Simple(); open (FILE, '>', "file.xml"); print FILE $xml->XMLout(\%zoo,noattr=>1,xmldecl=>'<?xml version="1.0"?>'); close FILE; print "------------------\n"; print "XML File\n"; print `cat file.xml`; print "------------------\n"; } sub display_zoo{ my $xml = new XML::Simple(); my $zoo=$xml->XMLin("file.xml"); print "------------------\n"; foreach my $animal (keys (%{$zoo->{'animals'}})){ print $zoo->{'animals'}->{$animal}->{'nickname'}; print " is a " . $zoo->{'animals'}->{$animal}->{'type'} . "\n"; } foreach my $staff (keys (%{$zoo->{'staff'}})){ print $zoo->{'staff'}->{$staff}->{'nickname'}; print " is a " . $zoo->{'staff'}->{$staff}->{'type'} . "\n"; } } sar:/# ./zoo.pl ------------------ Data Dump $VAR1 = { 'staff' => { '1' => { 'nickname' => 'mike', 'role' => 'manager' } }, 'animals' => { '1' => { 'nickname' => 'tom', 'type' => 'tiger' }, '2' => { 'nickname' => 'leo', 'type' => 'lion' } } }; ------------------ ------------------ XML File <?xml version="1.0"?> <opt> <animals> <name>1</name> <nickname>tom</nickname> <type>tiger</type> </animals> <animals> <name>2</name> <nickname>leo</nickname> <type>lion</type> </animals> <staff> <name>1</name> <nickname>mike</nickname> <role>manager</role> </staff> </opt> ------------------ ------------------ tom is a tiger leo is a lion Can't use string ("mike") as a HASH ref while "strict refs" in use at ./zoo.pl line 45. sar:/#
Direct Responses: 2864 | Write a response
Posted on Wed Aug 30 01:57:02 2006 by grantm in response to 2863
Re: Can't use string as HASH ref

The problem is that the data structure you're iterating is not the same as the one you dump out at the beginning. If you called Dumper after XMLin() rather than before XMLout() then this would be clear.

The reason the data structure is different is because you haven't specified a value for the ForceArray option. This article should help you understand what's going on.

PS: the Perlmonks site is a much better place to get your questions answered.

Write a response