Can I copy a hash without resetting its “each” iterator?

后端 未结 4 456
广开言路
广开言路 2020-12-07 00:59

I am using each to iterate through a Perl hash:

while (my ($key,$val) = each %hash) {
   ...
}

Then something interesting happ

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-07 01:18

    Let's not forget that keys %hash is already defined when you enter the while loop. One could have simply saved the keys into an array for later use:

    my @keys = keys %hash;
    
    while (my ($key,$val) = each %hash) {
    
        if (something_interesting_happens()) {
    
            print "$_ => $hash{$_}\n" for @keys;
        }
    }
    

    Downside:

    • It's less elegant (subjective)
    • It won't work if %hash is modified (but then why would one use each in the first place?)

    Upside:

    • It uses less memory by avoiding hash-copying

提交回复
热议问题