How can I assign two arrays to a hash in Perl?

前端 未结 4 1565
死守一世寂寞
死守一世寂寞 2020-12-08 09:48

I have lines of code with two large arrays (so can\'t just write it into a hash) which I want to connect with a hash.

For example, $array1[0] becomes th

4条回答
  •  爱一瞬间的悲伤
    2020-12-08 10:27

    (I tried posting this as a comment to brian's answer, but couldn't get the formatting right.)

    You have to be careful to avoid nested uses of each. each works on a "global" iterator on the array. When it reaches the end, it returns false and then resets the position to the beginning. Thus following code results in an infinite loop.

    Thanks to RJBS for his talk at YAPC::NA where he pointed out the global nature of the built-in iterator.

    use strict;
    use warnings;
    
    my @array = 'A' .. 'J' ;
    
    while ( my ($index, $value) = each @array){
            print "printing ($index, $value) from outer loop\n";
    
            while ( my ($index_in, $value_in) = each @array){
                    print "printing ($index_in, $value_in) from inner loop\n";
            }
    }
    

提交回复
热议问题