|
Returning multiple values from a function (Perl, PHP, Python)
Function in PHP and Python and subs in Perl can only return one "thing" - one item, one object. But all three languages allow that returned item to be a collection - in other words, a composite. And all three languages provide a very easy way of breaking the returned structure down into a series of individual variables.
Python Example returning a tuple
# Returning a tuple from a function
def doingit(v):
a = v+10
b= v*20
c = 56/v
return c,a,b; # returns a tuple
# function call will return a tuple (into z)
z = doingit(7)
# This syntax splits the tuple out into a
# series of individual variables (w, l and k)
w,l,k = doingit(7)
# Show that it has worked as expected
print w, l, k
print z
PHP Example returning into the list function
<?php
function maykit() {
$rv = array("4","15");
array_push($rv,"William");
return $rv;
}
list($fno,$sno,$name) = maykit();
print "We have $fno and $sno for $name\n";
?>
Perl Example Saving the returned values to a list
sub sistance {
my @n;
$n[0] = 4;
$n[1] = 17;
$n[2] = 23;
return @n;
}
($first,$second,$third) = sistance();
print "We have $first and $second and $third\n";
In each case, the techniques shown above should be used when you want to return multiple values in strong preference to global variables - your code will be much more modular and easy to maintain if you follow the approach shown. (written 2007-05-24 18:39:40)
Associated topics are indexed under H105 - PHP - FunctionsP209 - Subroutines in PerlY105 - Python - Functions, Modules and Packages
Some other Articles
Where and When - can you place the picture?Arrival and Departure experiences - another hotelSpot the differenceA Fresh horseReturning multiple values from a function (Perl, PHP, Python)No switch in PythonTraining information - England, Scotland, Wales and IrelandTesting for one of a list of values.From Web to Web 2Back off home with our best wishes
|
2259 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|