Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have inherited some code and am trying to introduce some error checking as I have been having some problems.

When I try to run the function, I receive the error.

"Not an ARRAY reference"

What is the best way to error check to make sure I have a valid array, Is it best to do this in the function? before it is returned? Code Snippet:
sub getID { my $url = shift; my $content = get($url); die "No: $url" unless $content; my $xmlsimple = XML::Simple->new( ); my $response = $xmlsimple->XMLin($content); return $response->{Item}->{ID}; }

Replies are listed 'Best First'.
Re: Error Checking for Array Reference
by davido (Cardinal) on Nov 06, 2005 at 05:30 UTC

    Maybe you could initialize XML::Simple like this:

    my $xmlsimple = XML::Simple->new( undef, ForceArray => 1 );

    That alters the datastructure somewhat, but helps to standardize it so that you don't have array-refs disappear just because there is only one element.


    Dave

Re: Error Checking for Array Reference
by bobf (Monsignor) on Nov 06, 2005 at 06:18 UTC

    For the example you posted and assuming you want $response->{Item}->{ID} to be an array ref, davido's solution is probably the easiest - just force XML::Simple to return an array regardless of the number of elements.

    If you need a more generalized solution, take a look at the ref function. It will allow you to check references like this:

    if( ref( $var ) eq 'ARRAY' ) { # $var is a ref to an array }

    HTH

Re: Error Checking for Array Reference
by pg (Canon) on Nov 06, 2005 at 06:34 UTC
    "Is it best to do this in the function? before it is returned?"

    In general, a function should first validate the input it gets before doing any processing. This is for sure the best practice, although people don't usually do this. bobf already pointed out how to validate refs.

Re: Error Checking for Array Reference
by jdporter (Paladin) on Nov 06, 2005 at 16:05 UTC

    Well, the code you posted has several statements, and you didn't say which one is the locus of the error. Just looking at the code, it's not even clear which statement would be assuming an array reference.

    We're building the house of the future together.