Wiggins has asked for the wisdom of the Perl Monks concerning the following question:
The code contains page references to HOP as to where the individual parts came from that I pulled together. For 5 hours, I couldn't get a successful run. The commented line labeled "!!! Important ..." was missing.
It was way back in the iterator chapter, and simply called "a bit of sugar". There is no explanation of that sort of magic it is causing the Perl interpreter to do. It seems to be a duplicate definition for the function 'Iterator' .
Can someone explain what this 'sugar' does and how?
Aside: While very "advanced", I would probably *not* use this technique due to the corresponding very high "obscure" and "unmaintainable" score.use strict; # Definition from HOP page 122 sub NEXTVAL { $_[0]->() } # HOP top of page 123, called "a bit of sugar" ??? #sub Iterator (&) { return $_[0] } #!!Important to make this work unc +omment!!! #HOP page 156 sub make_rand { my $seed = shift || (time & 0x7ffff); print "Seed=$seed\n"; return Iterator { #print " << $seed\n"; $seed = (13 * $seed + 31011) & 0x7ffffff; #print " >> $seed\n"; return $seed; }; } # My test code my $rng = make_rand(); # a reference to an "Iterator" code different # from the one defined originally ?? my @bucket; my $i; my $t; #printf " ==%d\n",(2**31); # HOP pages 156,7 for $i (1..10000){ my $rndx = NEXTVAL ($rng); #print " $rndx "; $rndx %= 100; #print " $rndx\n"; $bucket[$rndx] ++; } # test code $t=0; for $i (0..99) { print "$bucket[$i]- "; $t+=$bucket[$i]; } printf "\nAvg= %6.2f\n", $t/100; __END__
It is always better to have seen your target for yourself, rather than depend upon someone else's description.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: "a bit of sugar "(HOP)
by ig (Vicar) on Mar 13, 2009 at 19:00 UTC | |
by Wiggins (Hermit) on Mar 14, 2009 at 14:43 UTC | |
by ig (Vicar) on Mar 20, 2009 at 00:33 UTC | |
|
Re: "a bit of sugar "(HOP)
by JavaFan (Canon) on Mar 13, 2009 at 16:54 UTC | |
by Wiggins (Hermit) on Mar 13, 2009 at 18:15 UTC | |
by tilly (Archbishop) on Mar 13, 2009 at 18:22 UTC | |
by ikegami (Patriarch) on Mar 13, 2009 at 18:33 UTC | |
by hbm (Hermit) on Mar 13, 2009 at 18:41 UTC | |
| |
by JavaFan (Canon) on Mar 13, 2009 at 19:11 UTC | |
|
Re: "a bit of sugar "(HOP)
by CountZero (Bishop) on Mar 14, 2009 at 09:03 UTC |