Subroutine with arbitrary number of parameters


That would be the time to show how to define a subroutine that can get arbitrary number of values, but that requires introducing two concepts at a time. So I'll have to find a better set of examples. Anyway, if we would like to implement a sum() subroutine that can get any number of values we need to define it like this:

examples/subroutines/slurpy_argument.p6
#!/usr/bin/perl6
use v6;


sub sum(*@values) {
	my $sum = 0;
	for @values -> $v {
		$sum += $v
	}
	return $sum;
}

say sum(2, 3);      # 5

my @a = (2, 3, 4);
my $z = 5;
say sum(@a, $z);  # 14

That is, we have to say that the expected parameter is a slurpy array. The * means it is slurpy, the @ still means it is an array. It will then accept any value as parameter and put them in the @values array. So I can call it either with literal scalars or even with a list of arrays and scalars mixed


Copyright 2006, 2007, 2008, 2009, 2010 Gabor Szabo http://szabgab.com/ Index | TOC
If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed