in reply to Multiple Return Values

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")

Replies are listed 'Best First'.
Re: (tye)Re: Multiple Return Values
by John M. Dlugosz (Monsignor) on Jul 12, 2001 at 01:26 UTC
    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")