Returning multiple items from a sub?

R

robb

Hi,

I want to write a sub that returns a list of items so that the syntax
would like this:

my ($thing_one, $thing_two, $thing_three) = MyPackage->my_sub();

Is it possible to write a sub that can be used in this way? I haven't
figured it out.

Thanks.
 
S

Sisyphus

Hi,

I want to write a sub that returns a list of items so that the syntax
would like this:

my ($thing_one, $thing_two, $thing_three) = MyPackage->my_sub();

Is it possible to write a sub that can be used in this way? I haven't
figured it out.

package MyPackage;
use warnings;
use strict;

my ($thing_one, $thing_two, $thing_three) = MyPackage->my_sub();

print $thing_one, " ", $thing_two, " ",$thing_three, "\n";

sub my_sub {
my @ret = (5,7,9);
return @ret;
}

# or just:
#sub my_sub{ return (6, 8, 10)}

__END__

Cheers,
Rob
 
T

Tad McClellan

I want to write a sub that returns a list of items so that the syntax
would like this:

my ($thing_one, $thing_two, $thing_three) = MyPackage->my_sub();


So you want it to return a single flat list of scalars.

Is it possible to write a sub that can be used in this way?


Errr, yes. All subroutines/methods in Perl return lists (when called in
list context).

I haven't
figured it out.


There is no "figuring" needed, there is only "reading the first
couple paragraphs" of perlsub.pod, which is where you go to
learn things related to subroutines in Perl.


all functions likewise return to their caller one single flat
list of scalars.
 
J

Joe Smith

Is it possible to write a sub that can be used in this way? I haven't
figured it out.

If you want a function/method to return several things, then
you simple return several things. Period.

sub return_three_things {
...
return ($first,$second,$third};
}

What's so hard about that?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top