Shlomi Fish wrote:

On Wednesday 03 November 2010 09:27:14 shawn wilson wrote:
i'm getting errors when trying to print these hash refs out and i just
can't figure it out. here's the function:

for my $word ( keys %data ) {
    while( my ($field, $type) = each %{ $data }{ $word } ) {
       print "$word,$field" if( $type eq 'field' );
       while( my ($line, $type) = each %{ $data }{ $word } ) {
          print ",$line" if( $type eq 'line' );
       }
    }
}


1. each %{$data}{$word} is incorrect. You probably want:

each %{$data{$word}}.

And you may wish to do:

while (my ($word, $word_data) = each (%data)) {
        while (my ($field, $type) = each(%$word_data)) {

2. You are trying to iterate over %{$data{$word}} in two nested loops. This
will confuse Perl to no end.

No it will not.  Perl will know exactly what to do.

$ perl -le'
my %x = "a" .. "f";
my $count = 5;
while ( my ( $k1, $v1 ) = each %x ) {
    print "Loop 1: key=$k1 value=$v1";
    while ( my ( $k2, $v2 ) = each %x ) {
        print "\tLoop 2: key=$k2 value=$v2";
        }
    last unless --$count;
    }
'
Loop 1: key=e value=f
        Loop 2: key=c value=d
        Loop 2: key=a value=b
Loop 1: key=e value=f
        Loop 2: key=c value=d
        Loop 2: key=a value=b
Loop 1: key=e value=f
        Loop 2: key=c value=d
        Loop 2: key=a value=b
Loop 1: key=e value=f
        Loop 2: key=c value=d
        Loop 2: key=a value=b
Loop 1: key=e value=f
        Loop 2: key=c value=d
        Loop 2: key=a value=b



John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction.                   -- Albert Einstein

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to