Returning multiple values from a function call in various languages - a comparison
Archive - Originally posted on "The Horse's Mouth" - 2011-02-06 08:59:35 - Graham Ellis
I've always thought it a bit odd that you call a function with any number of parameters, and yet it returns a single value; in Java, C or C++ you declare a return type (void if there is not to be anything returned) and you are then constrained by that specification. There are, of course, other ways of returning data too. Most languages support some sort of global capability, or "call by reference" in which you can modify the incoming data and that alteration will also change the variable's contents as seen in the calling code. And in some languages such as Perl, special variables may be set within a function and the accessed outside.
But some languages do support multiple returns:
Ruby. If you return an array, and assign the result to more than one variable (in a comma separated list), the array will be unwrapped: smaller,larger = ben 10,20,30
See full code example [here]
Python. If you return a tuple, it can be split out into multuple variables: smaller,larger = ben(10,20,30)
See [here] - a previous article than includes a complete example
Perl. You can return a list (of several items) of a scalar from a sub, and you can use the misnamed wantarray function within the sub to determine the return type. You assign the returned value into a scalar or a list (remembering that assigning a list to a scalar will give you the length of the list!). There's an example in our course material [here] and you can assign the results to a named list of scalars if you wish: ($smaller,$larger) = ben(10,20,30)
PHP. If you return an array, you can assign it into a list function and store each of the returned members into its own variable: list($smaller, $larger) = ben(10,20,20);
You'll find this used in our real live global site index, for which we publish the source code (passwords changed!) [here]. There's a shorter example that uses this [here].
Before you start returning multiple values, though, think carefully. Should you be returning a single object instead?. A regular expression match in Perl returns a list of matched strings (if used in a list context). But in other languages (though you may have the option of multiple values back) you can also get back a single object from which you can request the elements that you need.