CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Advanced:
return %hash_or_ref ???



Jan 26, 2000, 8:49 AM

Post #1 of 5 (7595 views)
return %hash_or_ref ??? Can't Post

How do I correctly return a single hash from a sub??? Must it be by reference?
Is this right?

my %hash = &doit($some);

sub doit {
#blah blah blah
return %blah;


Jan 25, 2000, 10:10 PM

Post #2 of 5 (7595 views)
Re: return %hash_or_ref ??? [In reply to] Can't Post

Maybe this shouldn't be advanced... but I'm still a little shaky on refs... How's this look?

my $hashref_returned = &doit($some);

sub doit {
my $sql = shift;
# blah blah blah DBI
my $hashref_toreturn =
my $rc = $sth->finish;
return $hashref_toreturn;


Jan 26, 2000, 9:39 AM

Post #3 of 5 (7595 views)
Re: return %hash_or_ref ??? [In reply to] Can't Post

It is better if it is a reference but it can return as a hash like that.
All things that are passed to and from a subroutine are flatened into an array (@_). So catching a list with a hash is not a problem as long at the list has an even number of elements.


Enthusiast / Moderator

Jan 26, 2000, 3:38 PM

Post #4 of 5 (7595 views)
Re: return %hash_or_ref ??? [In reply to] Can't Post

If you want to use hash references, that is perfectly fine. However, this is one case where you can learn the magic of typeglobs.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

*hash = foo();
bar(*hash); # or bar(\%hash)

sub foo {
my %hash = ( ... );
return \%hash;

sub bar {
local *hash = $_[0];
# do stuff with %hash normally

Globs stop you from having to EXPLICITLY use references, or from having to COPY large data structures. However, since this isn't a copy, it is actually an alias:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

$a = "foo";
*b = *a;
$b = "bar";
print $a; # bar

$a = "foo";
@a = ("this","that");
*b = \@a;
$b = "bar";
push @b, "those";
print $a; # "foo"
print "@a"; # "this that those"

Typeglobs are discussed somewhat in perlref, and in more detail in perldata.


Feb 25, 2000, 2:14 PM

Post #5 of 5 (7595 views)
Re: return %hash_or_ref ??? [In reply to] Can't Post

I'd return a hash as a hash ref:

sub doit {
# create hash
\%hash ; # Return hash ref

This gives you maximum versatility:

%h = %{ &doit } ; # Return & deref hash in one go

$h = &doit ; # Return hash ref which you can later
print keys %{$h} ; # access by derefing or
%h = %{$h} # assign to another hash


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives