On Oct 31, Roy Peters said:
>Is there any way to return 2 or 3 scalar variables from a subroutine (like
>passing a variable by reference in C)?
>
>I would like to avoid returning an array, if possible, because it makes
>the script very non-intuitive.
Subroutines can return any number of arguments. You can even make a
function determine whether you called it as
$value = func();
or
($this, $that) = func();
so that you can return a specific single value, or a list. Take the
localtime() function as an example:
$date_string = localtime;
@date_parts = localtime;
That's done via the wantarray() function (which is a misnomer -- it should
be wantlist()):
sub func {
return "A B" if wantarray;
return ("A", "B");
}
When we use the func() code above, we set $value to "A B", and $this to
"A" and $that to "B".
As for returning things in general, you can return whatever you want. In
most cases, there's no difference between returning an array and returning
a list. If you're assigning to a list, they're pretty interchangeable:
sub list { return ('a', 'b', 'c') }
sub array { my @r = ('a', 'b', 'c'); return @r }
($this, $that, $those) = list();
($his, $hers, $theirs) = array();
@mine = list();
@yours = array();
There's no real difference here. There's no reason a function that
returns an array must return those values to ANOTHER array.
There is a small (but important) difference, though. When you call a
function in scalar context (like: $x = func()), returning an array causes
you to return the NUMBER OF ELEMENTS in the array:
sub array { my @r = ('a', 'b', 'c'); return @r }
@elements = array(); # 'a', 'b', 'c'
$size = array(); # 3
Compare that with return a list (or trying to):
sub array { return ('a', 'b', 'c') }
@elements = list(); # 'a', 'b', 'c'
$last = list(); # 'c'
That is the proper behavior, since using the comma operator in scalar
context returns the right-most term.
That's all for now... if you want to read more about context, you can
check out an article I'm written:
http://www.pobox.com/~japhy/articles/pm/2000-02.html
--
Jeff "japhy" Pinyan [EMAIL PROTECTED] http://www.pobox.com/~japhy/
RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]