home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / perl / 5599 < prev    next >
Encoding:
Internet Message Format  |  1992-08-29  |  1.9 KB

  1. Path: sparky!uunet!wupost!usc!news!lsi!mhost!up41!aspin
  2. From: aspin@lsil.com (David Aspinwall 7842)
  3. Newsgroups: comp.lang.perl
  4. Subject: Re: fast way to get number of elements in an assoc array?
  5. Message-ID: <1992Aug29.011345.24106@lsil.com>
  6. Date: 29 Aug 92 01:13:45 GMT
  7. References: <1992Aug27.152838.17427@news.eng.convex.com>
  8. Sender: news@lsil.com (news caster)
  9. Reply-To: aspin@lsil.com
  10. Organization: LSI Logic Corporation
  11. Lines: 52
  12. Nntp-Posting-Host: up41
  13. X-Newsreader: Tin 1.1 PL5
  14.  
  15. Tom Christiansen (tchrist@convex.COM) wrote:
  16. : Um, that doesn't tell you how many keys are in the array, just 
  17. : how full the hashtable is.  You have to do something more like
  18. :     $count++ while each %array;
  19.  
  20. I wrote a program to try various ways of doing this,
  21. including the one above, and get several different results.
  22. Can anyone explain this to me?
  23. Here's the program:
  24.  
  25.  
  26. #!/usr/up/sun4bin/perl
  27.  
  28. open(IN, "head -100 /usr/dict/words|");
  29. while (<IN>) {
  30.     $words{$_} = $nlines++;
  31. }
  32. close(IN);
  33. print "read $nlines lines\n";
  34.  
  35. &try('$n = keys(%words)');
  36. &try('$n = 0; while (each %words) { $n++; }');
  37. &try('$n = 0; $n++ while each %words;');
  38. &try('$n = 0; $n++ while (each %words);');
  39. &try('$n = 0; $n++ while (($w,$v) = (each %words));');
  40. &try('$n = 0; while (($w,$v) = each %words) { $n++; }');
  41. &try('$n = 0; while (($w,$v) = (each %words)) { $n++; }');
  42.  
  43.  
  44. sub try {
  45.     local ($cmd) = @_;
  46.     local ($n);
  47.     eval($cmd);
  48.     print "i get $n from\t$cmd\n";
  49. }
  50.  
  51.  
  52.  
  53. And here is the output:
  54.  
  55. read 100 lines
  56. i get 100 from    $n = keys(%words)
  57. i get 13 from    $n = 0; while (each %words) { $n++; }
  58. i get 86 from    $n = 0; $n++ while each %words;
  59. i get 13 from    $n = 0; $n++ while (each %words);
  60. i get 86 from    $n = 0; $n++ while (($w,$v) = (each %words));
  61. i get 100 from    $n = 0; while (($w,$v) = each %words) { $n++; }
  62. i get 100 from    $n = 0; while (($w,$v) = (each %words)) { $n++; }
  63.  
  64. --
  65.         -- David Aspinwall    aspin@lsil.com    408-433-7842
  66.