top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Retrieve hash between two subroutines in Perl

+1 vote
293 views

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

posted Mar 20, 2013 by Salil Agrawal

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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);
answer Mar 20, 2013 by Nora Jones
Similar Questions
0 votes

The following example doesn't compile:

use strict;
use warnings;

sub test {
 print $counter . "n";
}

my $counter = 0;
while($counter < 5) {
 test();
 $counter++;
}

It says "Global symbol "$counter" requires explicit package name ...". When I put the subroutine after the 'while' loop, it works just fine, so what's the problem?

+1 vote

I'm looking for a hash function and a related function or operator such that:

 H(string1 . string2) = f(H(string1), H(string2))
 H(string1 . string2) = H(string1) op H(string2)

 where:
 H() is the hash function    
 string1 is a string
 string2 is a string    
 . is the string concatenation operator 
 f() is a function
 op is a binary operator

Any suggestions?

+2 votes

I want to print one hash with one key undefined . I have condition print if key exist . I guess it should not print value for undefined key, but it does .

#!/usr/bin/perl -w

@array = ("abc", 123, "dfg" ,456, "xsd",undef);
%hash = reverse @array;

foreach $k (keys %hash){
 print "key $k value $hash{$k}n" if(exists $hash{$k});
 }

And another issue is , I want to write one line code for printing hash like below:

 print "key $k value $hash{$k}n" foreach $k (keys %hash);

But it fails with error :

syntax error at my_test.pl line 16, near "$k ("
Execution of my_test.pl aborted due to compilation errors.

Please point me where am I wrong?

...