簡體   English   中英

在Perl中將Hash鍵替換為另一個名稱

[英]Replacing Hash key with another name in perl

我正在嘗試用其他名稱更改密鑰。 嘗試以下代碼,但出現一些錯誤:

my @array = qw(1 hello ue hello 3 hellome 4 hellothere);
my %hash = @array;

foreach (Keys %hash) { 
   s/ue/u/g;
}

輸出錯誤:test.pl第35行的模數為零。

Perl區分大小寫。 您正在尋找keys (小寫):

my @array = qw(1 hello ue hello 3 hellome 4 hellothere);
my %hash = @array;

foreach (keys %hash) {  # <-- 
   s/ue/u/g;
}

您應該真正use strict; use warnings; use strict; use warnings; 在所有Perl模塊/腳本的頂部。 它將為您提供更好的錯誤消息。

更重要的是,您無法像這樣更新哈希鍵。 您必須使用所需名稱在哈希中創建一個新密鑰,然后刪除舊密鑰。 您可以在一行中很好地完成此操作,因為delete返回已刪除的哈希鍵的值。

use strict;
use warnings; 

my @array = qw(1 hello ue hello 3 hellome 4 hellothere);
my %hash = @array;

foreach my $key (keys %hash) {  # <-- 
   if ($key eq 'ue') {
      $hash{u} = delete $hash{$key};
   }
}

為了進一步加強代碼,實際上並不需要遍歷鍵來確定特定鍵是否存在。 以下單行可以代替for循環:

$hash{u} = delete $hash{ue} if exists $hash{ue};

暫無
暫無

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

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