Iterating through an array of hashes

前端 未结 2 1069
醉酒成梦
醉酒成梦 2021-01-28 01:19

I have wrote the below routine, to iterate through hashes 0 - 7 and print out the value of a specific key in each. I need to grab the value of \'b4\' in each hash.

I wo

相关标签:
2条回答
  • 2021-01-28 02:05

    Your $out is a reference to a single-element hash which has an array reference for the value of its data element

    It's best to extract the reference into a separate variable so that you can access the contents more simply. Suppose you wrote

    my $data = $out->{data};
    

    Thereafter, the array is accessible as @$data, the number of elements it contains is scalar @$data, and the indices are 0 .. $#$data. You can access each element of the array with $data->[0], $data->[1] etc.

    Your code would become

    my $out  = decode_json $client->responseContent;
    my $data = $out->{data};
    
    for my $i ( 0 .. $#$data ) {
        my $item = $data->[$i];
        my $b4 = $item->{b4};
        print "$b4\n";
    }
    

    But note that, unless you need the array index for other purposes, you are probably better off iterating over the array elements themselves rather than its indices. This code would do the same thing

    my $out  = decode_json $client->responseContent;
    my $data = $out->{data};
    
    for my $item ( @$data ) {
        my $b4 = $item->{b4};
        print "$b4\n";
    }
    

    Or even just

    print "$_->{b4}\n" for @$data;
    

    if you don't need to do anything else within your loop

    0 讨论(0)
  • 2021-01-28 02:17

    Here's how to iterate over the array

    for my $cur (@{$out->{data}})
    {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题