Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
My question to you wise and wonderful monks is whether I should return a hash or a hash reference.

Why lock your users into only one option? Thats not the perl way to do things.

If their code makes more sense with a ref then give them one, if it makes more sense to get a list of key=>value pairs then give it to them.

I avoid the term "to get a hash" as there is no way to return a hash from a subroutine. Instead the hash must be listified into key=>value pairs and then returned that way. Its up to the user to shove that list into an actual hash (or not).

And since this approach involves returning a list then good old perlfunc:wantarray comes to the rescue:

sub get_params { my $self = shift; my %input; $input{$_} = $self->{$cgi_handle}->param($_) foreach $self->{$cgi_handle}->param()); # we return a hashref if the user calls us in scalar context # or a list of key=>values pairs if they call us in list context. return wantarray ? %input : \%input; }
Incidentally this is a standard idiom that can come in very useful. Consider the behaviour of localtime(). You could even insert the following before the return statement
die "get_params in void context:".Dumper(\%input) unless defined wan +tarray;
to provide a debugging behaviour for when the sub is called in void context.

HTH

--- demerphq
my friends call me, usually because I'm late....


In reply to Re: Subroutines: Returning a hash vs. hash reference by demerphq
in thread Subroutines: Returning a hash vs. hash reference by mt2k

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2024-04-25 22:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found