Search code examples
perlhashargumentssubroutine

Retrieve hash between two subroutines


I would retrieve my hash table when i pass it in argument at a function. In my case, function1 return my hash table, then i pass my hash table in argument to my function2 and in my function2 i would retrieve my hash table for browse it.

sub function1{
    my code;
    return %hash;
}

sub function2{
    my %hash=$_[0];
    my code browse my hash;
}

my %hash = function1();
function2(%hash);

I have the following error : Odd number of elements in hash assignment at


Solution

  • An alternative is to pass the hash by reference:

    sub function1{
        # code here
        return \%hash;
    }
    
    sub function2{
        my $hashref = $_[0];
    
        #code to use the hash:
        foreach (keys %$hashref) { etc... }
    }
    
    my $hashref = function1();
    function2($hashref);
    
    my %realhash;
    function2(\%realhash);
    

    Passing by reference is a necessity when you want to pass more than one hash or array. It is also more efficient for large amounts of data, because it doesn't make a copy. However, if the function modifies a hash that was passed by reference, the original will be modified as well.