[Chicago-talk] return values

Steven Lembark lembark at wrkhors.com
Tue Dec 30 17:27:46 CST 2003



-- "Dooley, Michael" <Dooley.Michael at con-way.com>

> if you have multiple return values do you have to use an array to collect
> them? or can you get each return value in is own variable off the jump?
>
> sub stuff {
> $a=1;
> $b=2;
> return ($a, $b);
> }
>
> @c=stuff
>
> so
> $c=1st return value
> $d=2nd return value

The return value is the last value processed in the sub:

	sub foo
	{
		...

		( $a, $b )
	}


at that point:

	my @a = foo;

	my ( $i, $j ) = foo;

	my ( $first, @rest ) = foo;

will all happily take the list returned by foo and assign
it. Assigning to an array is nice if you want to iterate
the results; individual variables kind of assume you know
what is comming back (i.e., you'll loose a third value).

You can also use:

	croak "Bad news boss, foo returned nothing"
		unless my @a = foo;

	( $i, $j ) = @a;

to sanity check the returned values. Nice thing about
this is that the test for @a is kwik'n simple -- even
if it does waste a bit of time creating the array.

This is one of the reasons that people use referents to
return data more often now: you only have to keep track
of one return value:

	sub bar
	{
		...

		[ $i, $j, $k, @stuff ]
	}
	
	...

	my $result = bar @argz;

Hash referents are used for the same reason: you can name the
return values:

	sub bletch
	{
		...

		{ i => $i, j => $j, k => $j, list => \@argz }
	}

	...

	my $bletch_result = bletch;


	if( $bletch_result->{i} > 100 )
	{
		# whatever...

		die "i out of range: $bletch_result->{i}"
	}



--
Steven Lembark                               2930 W. Palmer
Workhorse Computing                       Chicago, IL 60647
                                            +1 888 359 3508



More information about the Chicago-talk mailing list