将哈希传递给已经传递该哈希的子例程内的子例程

时间:2014-03-18 19:43:00

标签: perl hash perl-data-structures

我正在将哈希传递给各种子程序,我想知道如何将哈希传递给子程序,然后将该子程序中的相同哈希传递给不同的子程序,依此类推。

例如,以下代码可以正常工作。

use strict;
use warnings;

my %hash = ( 
    key1 => 'value1',
    key2 => 'value2',
    key3 => 'value3',
    key4 => '', 
);      

print %hash, "\n"; 
check_it(\%hash);

sub check_it {
    my $params = shift; 

    foreach(keys %{$params}){        
        if($params->{$_}) {
            print "'$_' defined as '$params->{$_}'\n";
        }   
        else {
            print "'$_' not defined as '$params->{$_}'. Deleting it.\n"; 
            #delete $params->{$_};
            $params->{$_} = 'null';
        }     
    } 

    for ( my $i = 0 ; $i < 7 ; $i++ ) {
        print "looping\n";
        &check_tags_again(\%hash);
    }     
}   

sub check_tags_again {
    my $hash_now = shift;

    #check again...
    foreach(keys %{$hash_now}){
        print "An element of hash: ", $hash_now->{$_}, "\n";
        #if(defined $hash_now->{$_}){ delete $hash_now->{$_};}
    }
    &check_tags_thrice(\%hash);
}   

sub check_tags_thrice {
    my $hash_now = shift;

    #check again...
    foreach(keys %{$hash_now}){
        print "An element of hash: ", $hash_now->{$_}, "\n";
        #if(defined $hash_now->{$_}){ delete $hash_now->{$_};}
    }   
}   

print "final hash:", %hash, "\n";

但是,当我运行以下代码时:

use strict;
use warnings;
use Data::Dumper;

sub process_data {

    my $group_size = 10; 

    my %HoA = ( 
        flintstones => [ "fred",   "barney" ],
        jetsons     => [ "george", "jane", "elroy" ],
        simpsons    => [ "homer",  "marge", "bart" ],
    );      

    &delete_stuff( \%HoA, $group_size );
    print "New group:\n";
    print Dumper( \%HoA );
    undef %HoA;
}   

sub delete_stuff {
    my $HoARef     = shift;
    my $group_size = shift;

    print "group size in sub $group_size\n";

    for ( my $j = 0 ; $j < $group_size ; $j++ ) { 
        my $dlted = &delete_other_stuff( \%HoA, $j );
        print "deleted? '$dlted'\n";

        if ( $dlted == 0 ) { 
            &presence_check( \%HoA, $j );
        }   

        for ( my $i = 0 ; $i < $group_size ; $i++ ) { 
        }   
    }   
}   

sub delete_other_stuff {
    my $HoAref  = shift;
    my $Dex     = shift;
    return $deleted;
}   

sub presence_check {
    my $HoAreF = shift;
    my $DeX    = shift;
}

我明白了:

 Global symbol "%HoA" requires explicit package name at x.pl line 32.
 Global symbol "%HoA" requires explicit package name at x.pl line 35.
 Execution of x.pl aborted due to compilation errors.

我很困惑,因为我认为它与第一个做同样的事情,但现在声称%HoA从未初始化。

1 个答案:

答案 0 :(得分:5)

delete_stuff,您没有%HoA,您有$HoARef。如果所有的subs都期望对哈希的引用,那么你可以使用它:

for ( my $j = 0 ; $j < $group_size ; $j++ ) { 
    my $dlted = &delete_other_stuff( $HoARef, $j );
    print "deleted? '$dlted'\n";

    if ( $dlted == 0 ) { 
        &presence_check( $HoARef, $j );
    }
    ...
}

顺便说一下,我们已经关闭了20年的Perl 5.没有理由用明确传递参数&来调用sub,这是一个Perl 4保持模式。