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

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
If I understand you correctly, you only want to return a scalar from this function if it is called with only one argument. What I'm thinking of is a function that, when called with one argument returns a scalar and when called with multiple arguments returns an array. Then you could just have sth like this:
sub foo { my @args = @_; # do your calculation if (@args != 1) { return @results; } else { return $results[0]; # or return $result; # depending on your calculation } }
It depends on what your function is doing. The problem with the wantarray solution is that you are calculating an array of results but not giving everything back to the user - whether you return the first or the last element, it's lying, because you actually had more results calculated in the sub.

What I'm trying to say: the user is normally expecting an array returned from that sub. So he might on purpose write sth like my $length = foo(1,2,3); to get the amount of results. This user might then be surprised if he gets the first (or last) element of the array instead. If you return the whole array then he could still choose the get only the first (or last value) or any value in between like so:my $value = ( foo(1,2,3) )[$i];

Just a few thoughts ...

-- Hofmator


In reply to Re: Context aware functions - best practices? by Hofmator
in thread Context aware functions - best practices? by Aristotle

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 chilling in the Monastery: (3)
As of 2024-04-19 21:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found