Reputation: 301
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
Upvotes: 0
Views: 64
Reputation:
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.
Upvotes: 1
Reputation: 23075
You are only pulling in the first element of a list into a hash (i.e. an even sized list, hence the warning). Try this:
sub function1{
my code;
return %hash;
}
sub function2{
my (%hash) = @_;
my code browse my hash;
}
my %hash = function1();
function2(%hash);
You can get what you want with a hashref:
sub function1{
my code;
return \%hash;
}
sub function2{
my $hash_ref=$_[0];
my code browse my hash;
}
my $hash_ref = function1();
function2($hash_ref);
Upvotes: 2