Table of Contents

Returning arrays

So that's the end of subroutines and parameters. Would you believe I have only scratched the surface? There are closures, prototypes, autoloading and references to learn. Not, however, in this tutorial. At least not yet. I'll finish with one last demonstration. You may have noticed that Perl returns one long list from subroutines. This is fine, but suppose you want two separate lists, for example two arrays? This is one way to do it:

($w1,$w2)=&wordfunc("Hello World");	# Assign the array references to scalars

print "@$w1 and @$w2\n";		# deference, ie access, the arrays referred to
#print "$w1 and $w2\n";			# uncomment this next time round

sub wordfunc {
        my $phrase=shift;
	my (@words,@word1,@word2);	# declare three variables lexically
	@words=split /\s+/,$phrase;	# split the phrase on whitespace
	@word1=split //,$words[0];	# create array of letters from the first word
	@word2=split //,$words[1];	# and the second
	return (\@word1,\@word2);	# return references to the two arrays -- scalars
}

There is a lot going on there. It should be clear up until the return statement. As we know, Perl only returns a single list. So, we make Perl return a list of the arrays it has just created. Not the actual arrays themselves, but references to the arrays. A bit like a shopping list is a just a bit of paper, not the actual goods itself. The reference is created by use of the \ backslash.

Having returned two array references they are assigned to scalar variables. If you uncomment the second print line you'll see two references to arrays.

The next problem is how to dereference the references, or access the arrays. The construct @$xxx does that for us. I know I said I wouldn't cover references, and I haven't -- that is just a useful trick.

This little section is not designed as a complete guide, it is just a taster of things to come. Perl is immensely powerful. If you think something can't be done, the problem is likely to be it is beyond your ability, not that of Perl.