Forum Moderators: coopster & phranque

Message Too Old, No Replies

Anonymous hashed array

Is it an array . . . or isn't it?

         

rocknbil

9:17 pm on Apr 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've been doing this for years but now and then things get befuddled in me' noggin.

USPS XML shipping response: if you request all available services for a package, you get something like


$data = {
'Package' => {
'ID' => '0',
'ZipDestination' => '10022',
'Ounces' => '0',
'Postage' => [
{
'Rate' => '41.30',
'MailService' => 'Express Mail PO to Addressee'
},
{
'Rate' => '14.40',
'MailService' => 'Express Mail Flat Rate Envelope (12.5" x 9.5")'
}
]
,
'ZipOrigination' => '12345',
'Zone' => '8',
'Error' => {},
'Size' => 'REGULAR',
'Pounds' => '11',
'Machinable' => 'FALSE'
}
};

Note the bolded, this is an array to parse as in

foreach $e (@{$data->{Package}->{Postage}}) {
push (@rates, ($e->{Rate} * $num_boxes));
push (@mail, $e->{MailService});
}

So I have two neat arrays of rates and services to display.

The problem: Sometimes there is only one service available:


$data = {
'Package' => {
'ID' => '0',
'ZipDestination' => '12345',
'Ounces' => '8',
'Postage' => {
'Rate' => '127.24',
'MailService' => 'Parcel Post'
},
'ZipOrigination' => '12345',
'Zone' => '8',
'Error' => {},
'Size' => 'OVERSIZE',
'Pounds' => '62',
'Machinable' => 'FALSE'
}
};

If the above method is used, 'foreach $e (@{$data->{Package}->{Postage}})' of course errors because it's not an ARRAY reference. I never know when this is going to return a single possible result, so it has to be able to identify if there's an array. I know there's got to be an easy way to identify this as an array but it fails me. if (@{$data->{Package}->{Postage}}) and if (defined(@{$data->{Package}->{Postage}})) both fail. What am I missing? :-(

rocknbil

10:41 pm on Apr 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



A helpful workaround . . . . probably not the "right" or "best" . . . .

$ref = ref($data->{Package}->{Postage});
if ($ref eq 'ARRAY') { $isArray = 1; }

perl_diver

9:35 pm on Apr 8, 2007 (gmt 0)

10+ Year Member



A helpful workaround . . . . probably not the "right" or "best" . . . .

thats pretty much the only way, use the ref() function to determine the data type and proceed from there.