Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

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!

Replies are listed 'Best First'.
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
Re: Returning hash reference from a sub
by tobias_hofer (Friar) on Mar 18, 2013 at 13:47 UTC


    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.

      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 };

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1024034]
Approved by marto
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (13)
As of 2017-07-25 20:13 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (377 votes). Check out past polls.