Search code examples
perlsubroutine

can someone explain how this reference function work with this perl subroutine?


this is the sub routine which i could not understand , i tried to pass some array and hash as argument but could not figure it out

sub List {

        my $value = shift;
        my $key = shift; 

     if (ref($value->{$key}) eq ARRAY) {

        $value->{$key}
     }
     elsif (ref($value->{$key}) eq HASH) {
        [$value->{$key}]
     }
     else { [
     ]
     }
    }

Solution

  • The first argument is expected to be a reference to a hash.

    The second argument is the key of an element of the referenced hash.

    If the element's value is a reference to an array, that reference is returned.

    my @a = ...;
    my %h = { key => \@a };
    List(\%h, 'key')   # Returns \@a
    

    If the element's value is a reference to an hash, a reference to an array containing that hash reference is returned.

    my %inner = ...;
    my %h = { key => \%inner };
    List(\%h, 'key')   # Returns [ \%inner ]
    

    Otherwise, returns a reference to an empty hash

    my %h = { };
    List(\%h, 'key')   # Returns []