After reading tye's comment on how he likes it, I started thinking that (1) the more variations I add, the more complex the code gets, and (2) a reusable helper would be great.

So, here is a first draft of a helper function that will package up return values based on 4 different situations. I really like the idea of specifying which return values you want and in what order. It cuts through the whole issue of remembering the long list and arranging it properly. To better support reuse, I made it take a list as individual params or a list ref. If you give it nothing, it returns the whole thing, the way typical list-valued functions do now. If you pass it a hashref, it populates it and returns undef.

Let me know what y'all think, and I'll make a more polished version later. The next question, then, is what should I call the module, or what existing module can it be added to?

—John

(code follows)

# Multiple Return Value concept code use strict; use warnings; use Carp; sub _populate_hash { my $hash= shift; my @values= @{shift(@_)}; my @names= @{shift(@_)}; croak unless scalar @values == scalar @names; while (@values) { $hash->{shift @names}= shift @values; } } sub create_multiple_return # call this from the function you want to work this way. { my $retlist= shift; # first parameter is list ref of all values my $namelist= shift; # second parameter is list of names of those va +lues my $wantnames; # remaining arg list is what caller supplied on the host function: # either hash ref, list ref, or individual strings, or empty. ### (1) call with no args to return entire list. return @$retlist unless @_; my $paramtype= ref $_[0]; ### (2) call with hash ref populates the hash. if ($paramtype eq 'HASH') { _populate_hash ($_[0], $retlist, $namelist); return; } my %vals; _populate_hash (\%vals, $retlist, $namelist); ### (3) call with individual strings, make look same as case 4. unless ($paramtype) { # scalar $wantnames= \@_; } else { ### (4) list of value names to return $wantnames= shift; croak unless ($paramtype eq 'ARRAY'); carp "too many params" if @_; } return map { croak unless exists $vals{$_}; $vals{$_} } @$wantnames; } ############# # example data { my @namelist= qw/year month day hour minute second/; my @vallist= qw/2001 July 10 1 2 30/; sub get_time { my $ignored_argument= shift; return create_multiple_return (\@vallist, \@namelist, @_); } } my $Param= 5; # show how IN parameters are before the stuff this modu +le deals with. my @A= get_time($Param); # (1) get all return values in pre-defined o +rder. print "@A\n"; @A= get_time ($Param, qw/second year hour/); # (3) specify list of de +sired values, in desired order. print "@A\n"; my @wantnames= qw/month year/; @A= get_time ($Param, \@wantnames); # (4) single ref to list instead +of individual params print "@A\n"; my %hash; get_time ($Param, \%hash); # (2) populate hash foreach (keys %hash) { print "$_ => $hash{$_} "; } print "\n";

Replies are listed 'Best First'.
(tye)Re: Multiple Return Values
by tye (Sage) on Jul 12, 2001 at 01:08 UTC

    The code I use looks like this:

    my @opts= qw( This That TheOther Else Foo Bar Blatz ); my %opts; @opts{@opts}= 1x@opts; sub GetOptions { my $self= shift(@_); my $href= {}; $href= shift(@_) if @_ && UNIVERSAL::isa($_[0],"HASH"); @_= @opts if ! @_; foreach my $opt ( @_ ) { croak ref($self),"->GetOptions: Invalid option ($opt) ", "not one of ( @opts )" unless $opts{$opt}; $href->{$opt}= $self->Get($opt); } return @{$href}{@_}; }
    except that %opts actually contains references to "get" methods.

    For your helper code I suggest this change:

    sub _populate_hash { my $hvHash= shift(@_); my $avValues= shift(@_); my $avNames= shift(@_); croak unless @$avValues == @$avNames; @{$hvHash}{@$avNames}= @$avValues; }
    or just use a hash slice directly in the caller.

            - tye (but my friends call me "Tye")
      Re hash slice: thanks for pointing that out. It's much cleaner than mapcar. I also like how you did the internal vs supplied hash--I had pondered always using an inside one and assigning it to the dereferenced param, but thought that was gross.

      It looks like your code is for returning things from a class, like what you can do with Tk widgets, right?

      I'm thinking of something that naturally creates a list, like gmtime. I suppose if you had a time object instead, you wouldn't have the problem of returning 8 scalars in the first place.

      —John

        Thanks. Yes, that example is OO. Here it is reworked non-OO:

        my @opts= qw( second minute hour day month year weekday yearday isdst ); my %opts; @opts{@opts}= 0..$#opts; sub LocalTime { my $time= shift(@_); my @values= localtime($time); return @values if ! @_; # Optional but may save CPU (: my $href= {}; $href= shift(@_) if @_ && UNIVERSAL::isa($_[0],"HASH"); @_= @opts if ! @_; foreach my $opt ( @_ ) { croak "LocalTime: Invalid option ($opt) not one of ", "( @opts )" unless defined $opts{$opt}; $href->{$opt}= $values[$opts{$opt}]; } return @{$href}{@_}; }
        Note that these versions let you do interesting things like:
        my $year= LocalTime( time(), \(my %time), qw( second minute hour day month year ) );

                - tye (but my friends call me "Tye")