develooper Front page | perl.beginners | Postings from April 2008

Re: going through array of hash, it only goes through limited amountof keys while doing for each command

Thread Previous | Thread Next
From:
Richard Lee
Date:
April 23, 2008 12:30
Subject:
Re: going through array of hash, it only goes through limited amountof keys while doing for each command
John W. Krahn wrote:
> Richard Lee wrote:
>>
>> something is wrong with this..
>>
>> say %yahoo's key contains the variable , X
>>
>> I wanted to go through the @array which has array of hashes... to see 
>> if one of the value is equal to
>> X and if it is, wanted to assign the key of the @array to $ex_var..
>>
>> Tracing the program, it only goes through 6 lines of keys in @t_array 
>> (random keys) (it has 89 keys total).. what am i doing wrong?
>>
>>
>>
>>
>>      while (my ($keys,$values) = each(%yahoo) ) {
>>              no strict 'refs';
>>              MF: for my $i (0 .. $#t_array) {
>>                      for ( my($k,$v) = each(%{ $t_array[$i] } ) ) {
>
> The for loop is not doing what you appear to think it is supposed to 
> be doing:
>
> $ perl -le'
> my %hash = "A" .. "Z";
> for my $c ( 1 .. 3 ) {
>     my $i;
>     for ( my ( $k, $v ) = each %hash ) {
>         print "$c ", ++$i, qq[: \$_ = "$_"   \$k = "$k"   \$v = "$v"];
>         }
>     }
> '
> 1 1: $_ = "S"   $k = "S"   $v = "T"
> 1 2: $_ = "T"   $k = "S"   $v = "T"
> 2 1: $_ = "A"   $k = "A"   $v = "B"
> 2 2: $_ = "B"   $k = "A"   $v = "B"
> 3 1: $_ = "O"   $k = "O"   $v = "P"
> 3 2: $_ = "P"   $k = "O"   $v = "P"
>
>
> You need to use each() in a while loop instead.
>
>
>>                          my $keys_b = qr/$keys/;
>>                          if ( $v  =~ m/$keys_b/ ) {
>>                              $ex_var = $k;
>>                              last MF;
>>                      }
>>                   }
>>              }
>
>
> John



      while (my ($keys,$values) = each(%yahoo) ) {
              no strict 'refs';
              MF: for my $i (0 .. $#t_array) {
                     for ( my($k,$v) = each %{ $t_array[$i] } ) {
                     #  for ( my($k,$v) = each %t_array ) {
                          my $keys_b = qr/$keys/;
                          if ( $v  =~ m/$keys_b/ ) {
                              $ex_var = $k;
                              last MF;
                      }
                   }
              }


while @t_array contains

%something = (
            "something1" => "123",
            "something2" => "234",
                ..... so and on
);

%something_now = (
            "something11" => '123123',
            "something222" => '2134',
)

@t_array = (\%something, \%someting_now)

Thread Previous | Thread Next


Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About