>>>>> "GJ" == Greg J <greg.jar...@gmail.com> writes:
GJ> Hi everyone, GJ> I am new to Perl and I am having some trouble working with hashes of hashes. GJ> I am trying to write a simple Markov Chain text generator and thought GJ> it might be a good idea to keep track of state transitions in a hash. GJ> Here is some of the code I have.. GJ> ==================================== GJ> use Data::Dumper; GJ> my %StateTable = (); GJ> sub InsertWord GJ> { GJ> my( $state, $next ) = shift @_; that is very wrong. either use shift to get one arg or assign @_ to a list to get all of them. you used both styles so $next is never set to anything (stays undef). GJ> if( $StateTable{$state} ) GJ> { GJ> if( $StateTable{$state}{$next} ) GJ> { GJ> $StateTable{$state}{$next}++; GJ> }else{ GJ> $StateTable{$state} = { $next => 1 }; GJ> } you don't need the if/else as ++ will work on an undef entry and set it to 1. it won't even trigger a warning as this is a common and useful idiom. GJ> }else{ GJ> $StateTable{$state} = { $next => 1 }; and you can also dispense with that if/else. just use ||= which won't assign if it already has a true value and refs are always true. this should replace all the above code (untested): $StateTable{$state} ||= { $next => 0 }; $StateTable{$state}{$next}++; note that i set the value to 0 so the ++ will set it to 1. for more on hashes of hashes read perldoc perlreftut, perllol and perldsc. uri -- Uri Guttman ------ u...@stemsystems.com -------- http://www.sysarch.com -- ----- Perl Code Review , Architecture, Development, Training, Support ------ --------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com --------- -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/