Search code examples
arraysperlhashsubroutine

Optionally return either an array or a hash from a subroutine?


How can I return either a hash or an array from a subroutine, depending on what the user wants?

Basically I want a subroutine that when asked to return a hash it will return a hash, but when asked to return an array it will return an array containing what would be the keys of that hash.

ex:

my %hash = foo();

my @array = foo();  # @array contains "keys %hash"

# pseudo code
sub foo {

     # Define a hash
     my %hash = (
         'key1' => 'val1',
         'key2' => 'val2',
         'key3' => 'val3',
     );

     # I know this is not valid Perl code, but it represents what I want.
     return keys %hash if wantarray;
     return %hash      if wanthash;
}

I know you can use wantarray to determine whether you want an array or a scalar to be returned, but I need a similar functionality for optionally returning an array or a hash.


Solution

  • Your subroutine may return array or reference to hash.

    my @array = foo();  # @array contains "keys %hash"
    my $hash_reference = foo();
    
    print $array[0],"\n"; # keys returned by foo are in random order
    print $hash_reference->{key1},"\n";
    
    
    # sample code
    sub foo {
    
         # Define a hash
         my %hash = (
             'key1' => 'val1',
             'key2' => 'val2',
             'key3' => 'val3',
         );
    
         if( wantarray) {
             return keys %hash;
         }else{
             return \%hash
         }
    }