零零乙 2008-08-06 02:53 采纳率: 33.3%
浏览 209
已采纳

循环访问 Perl 散列的键的最安全的方法是什么?

If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using each may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way?

# Method 1
while (my ($key, $value) = each(%hash)) {
    # Something
}

# Method 2
foreach my $key (keys(%hash)) {
    # Something
}

转载于:https://stackoverflow.com/questions/3033/whats-the-safest-way-to-iterate-through-the-keys-of-a-perl-hash

  • 写回答

9条回答 默认 最新

  • ℙℕℤℝ 2008-08-06 13:22
    关注

    The rule of thumb is to use the function most suited to your needs.

    If you just want the keys and do not plan to ever read any of the values, use keys():

    foreach my $key (keys %hash) { ... }
    

    If you just want the values, use values():

    foreach my $val (values %hash) { ... }
    

    If you need the keys and the values, use each():

    keys %hash; # reset the internal iterator so a prior each() doesn't affect the loop
    while(my($k, $v) = each %hash) { ... }
    

    If you plan to change the keys of the hash in any way except for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys():

    %h = (a => 1, b => 2);
    
    foreach my $k (keys %h)
    {
      $h{uc $k} = $h{$k} * 2;
    }
    

    producing the expected resulting hash:

    (a => 1, A => 2, b => 2, B => 4)
    

    But using each() to do the same thing:

    %h = (a => 1, b => 2);
    
    keys %h;
    while(my($k, $v) = each %h)
    {
      $h{uc $k} = $h{$k} * 2; # BAD IDEA!
    }
    

    produces incorrect results in hard-to-predict ways. For example:

    (a => 1, A => 2, b => 2, B => 8)
    

    This, however, is safe:

    keys %h;
    while(my($k, $v) = each %h)
    {
      if(...)
      {
        delete $h{$k}; # This is safe
      }
    }
    

    All of this is described in the perl documentation:

    % perldoc -f keys
    % perldoc -f each
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)