通过引用访问“散列哈希”的内部值

时间:2014-09-22 08:02:48

标签: perl

我有一个Hash of Hashes,我发送到subroutin并且我想访问它的键及其值(键和值)。

我有:

sub replace_sub {
    my ( $result_dir, $FilesHash ) = @_;
    foreach my $file ( keys %{$FilesHash} ) {
        open( INPUT_FILE, "$result_dir/$file" ) or die "Can't create output file\n";
        my @LINES = <INPUT_FILE>;
        open( my $output_file, ">", "$result_dir/$file" ) or die "Can't create output file\n";
        foreach my $myline ( keys %{ $FilesHash{$file} } ) {
            for ( my $i = 0; $i <= $#LINES; $i += 1 ) {
                if ( $LINES[$i] =~ m/$myline/ ) {
                    my $line = $LINES[$i];
                    $LINES[$i] =~ s/\Q$line\E/\/\/  $line  $FilesHash{$file}{$myline}\n/g;
                }
            }
        }
        print $output_file @LINES;
        close(INPUT_FILE);
        close($output_file);
    }
}

但是我不知道如何访问内部哈希的值, 试图这样做的代码行是:

my $myline ( keys %{ $FilesHash{$file} } )

$LINES[$i] =~ s/\Q$line\E/\/\/  $line  $FilesHash{$file}{$myline}\n/g;

我该如何访问它们?

我打算用这种方式调用subroutin:

replace_sub ($result_dir, \%Hash)

2 个答案:

答案 0 :(得分:3)

use strict;会告诉您%FilesHash没有$FilesHash这样的东西是hashref,因此

$FilesHash{$file}

应替换为

$FilesHash->{$file}

答案 1 :(得分:0)

在迭代哈希时可以使用each()

while ( ( $key1, $value1 ) = each %{$FilesHash} ) {
    while ( ( $key2, $value2 ) = each %{$value1} ) {
        print "[$key1] $key2 => $value2\n";
    }
}

N.b。您可能会发现这更具可读性,但不是每个人都认为这是“好”的做法(阅读评论@tobyink)