Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Returning hash reference from a sub

by Anonymous Monk
on Mar 18, 2013 at 13:35 UTC ( #1024034=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I am trying to return a has reference from this sub, but it seems that this is not the right way of doing it, can someone tell what is the best way to accomplish this even without pushing it into an array in the while loop, is its possible?
sub names{ ... my @loop_data = (); # initialize an array while ( my $row = $data_handle->fetchrow_hashref ){ my %row_data; # get a fresh hash for the row data # fill in this row $row_data{names} = $row->{'names'} || ''; # push a reference to this row into the loop! push(@loop_data, \%row_data); } my %final_data; if(!@loop_data) { push @loop_data, {names => 'No names'}; %final_data = @loop_data; return \%final_data; }else { %final_data = @loop_data; return \%final_data; } }
Thanks for looking!

Comment on Returning hash reference from a sub
Download Code
Re: Returning hash reference from a sub
by tobias_hofer (Friar) on Mar 18, 2013 at 13:47 UTC

    Hi,

    I am usually directly using references to anonymous hashes, like this:

    while ( my $row = $data_handle->fetchrow_hashref ){ my $row_data = {}; # get a fresh hash for the row data # fill in this row $row_data->{names} = $row->{'names'} || '';
    And at the end I simply do return $row_data this is working fine for me.
    Cheers
    Tobias

      Yes, but I am still stuck with only one row of data, I need to get all the data from the while loop and return it from the sub.
        ... %final_data = @loop_data; ...

        What is this line supposed to do?

        Please also explain how you intend to use the data stored in %final_data.

        Maybe you wanted to use the following construct instead?

        return { names => \@loop_data };
Re: Returning hash reference from a sub
by blue_cowdawg (Monsignor) on Mar 18, 2013 at 14:37 UTC

    seems to me you are going to a lot of trouble to return a single row.

    #sniglet # # somewhere in your while loop return { names => $row->{names} } if $row->{names};

    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (8)
As of 2014-09-16 22:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (51 votes), past polls