Main Content

Returning multiple values from a function (Perl, PHP, Python)

Archive - Originally posted on "The Horse's Mouth" - 2007-05-24 18:39:40 - Graham Ellis

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.