Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

array expected hash given

by kosta (Sexton)
on Feb 14, 2011 at 20:32 UTC ( [id://888053]=perlquestion: print w/replies, xml ) Need Help??

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

Hi,
I have a db output (done by fetchall_arrayref) and I want to parse it in my module function if I call
my $res= $db->select('SOME SELECT') $my_module-> parse ($res, $something_else); #this is my parse function in the module: my ($resource, $something ) = @_; ... for (my $i=0; $i<scalar($resource); $i++) { #some code }
it dies on scalar($resource) saying "Not an ARRAY reference at ..." When I printed it out it turns out that if I do print $res in my script it says ARRAY(0xSOMETHING) if I do it in the module print $resource it says HASH(somethingXsomething)
SO what is up with that? It is an array that gets passed as a hash?!

Replies are listed 'Best First'.
Re: array expected hash given
by TomDLux (Vicar) on Feb 14, 2011 at 20:39 UTC

    The $my_module becomes the $self argument in the parse routine, and that's what you're assigning to $resource. You need to do ...

    sub parse { my ( $self, $resource, $something ) = @_; ... }

    update: You can't do scalar on an array reference, you have to access the underlying array, THEN you can use a scalar context. You don't need to explicitly specify scalar context here, though it might be clearer for team mates who are less accustomed to getting the array size by using the array as a scalar. My preference, and common modern usage, is to use a number range rather than a C-style for loop, though it isn't wrong to do so ... you'll just have people mentioning 'modern usage' to you. You CAN simply use @$resource, but I have perltidy configured to remind me to use curly braces when using multiple sigils, because it clarifies more complicated cases. I wouldn't mind tolerating @$resource, but consistency MAY assist team members who are less comfortable with it, so I stick in the curlies.

    for my $i ( 0..@{$resource} - 1 ) { ... }

    As Occam said: Entia non sunt multiplicanda praeter necessitatem.

      Thanks :_ It really helped and I was able to get it working :)
Re: array expected hash given
by ciderpunx (Vicar) on Feb 14, 2011 at 20:58 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://888053]
Approved by chrestomanci
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-19 07:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found