簡體   English   中英

將數組添加到Perl中的哈希

[英]Add array to hash in perl

我嘗試在哈希中添加數組。

if ( not exists $hashtime{ $arr[0] }{ $date }{ $hour }{ $min } ) {
    print "$min not exist";
    $hashtime{ $arr[0] }{ $date }{ $hour }{ $min } = [ $sec ];
    $create++;
};

並收到錯誤:

在./sort_log_by_ip.pl第63行,第1行處不是HASH引用。

為什么此代碼錯誤?

perldoc perldsc我看到了這種構造,並且我正在使用類似的東西:

while ( <> ) {
     next unless s/^(.*?):\s*//;
     $HoA{$1} = [ split ];
}

更新

之前的代碼:

if ( not exists $hashtime{ $arr[0] } ) {
    $hashtime{ $arr[0] } = ( $date => { $hour => { $min => [ $sec ] } } );
    $create++; 
    print "create for IP: $arr[0]\n";
}

if ( not exists $hashtime{ $arr[0] }{$date} ) {
    $hashtime{ $arr[0] }{ $date } = ( $hour => { $min => [ $sec ] } );
    $create++;
    print "create for IP: $arr[0] DATE: $date\n";
}

if ( not exists $hashtime{ $arr[0] }{$date}{$hour} ) {
    $hashtime{ $arr[0] }{ $date }{ $hour } = ( $min => [$sec] );
    $create++;
    print "create for IP: $arr[0] DATE: $date HOUR: $hour\n";
}

在所有if塊中,您都使用列表( )代替哈希引用{ }

當你說

$hashtime{$arr[0]} = ( $date => { $hour => { $min => [$sec] } } );

由於在標量上下文中對LIST ( )進行了評估,因此發生的情況等同於

$hashtime{$arr[0]} = ( $date, { $hour => { $min => [$sec] } } );

最終成為

$hashtime{$arr[0]} = { $hour => { $min => [$sec] } };

因為,運營商評估並丟棄操作數一次一個,返回的最后一個。

下一個if類似,則您可以選擇其中一個(或兩個都選擇)

$hashtime{$arr[0]}{$date}{$min}{[$sec]}
$hashtime{$arr[0]}{$hour}{$min}{[$sec]}

但是,導致錯誤的代碼

if (not exists $hashtime{$arr[0]}{$date}{$hour})

$arr[0]{$date}都需要一個hashref,但顯然沒有兩者。


在兩個if塊中,您都需要分配一個使用{ }獲取的哈希引用

$hashtime{$arr[0]} = { $date => { $hour => { $min => [$sec] } } };

$hashtime{$arr[0]}{$date} = { $hour => { $min => [$sec] } };

以及最后一個if塊。


請正確縮進您的代碼。 以它的發布方式來處理它非常困難。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM