home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / perl / 5576 < prev    next >
Encoding:
Text File  |  1992-08-27  |  1.9 KB  |  51 lines

  1. Newsgroups: comp.lang.perl
  2. Path: sparky!uunet!mcsun!sunic!corax.udac.uu.se!irfu.se!jhd
  3. From: jhd@irfu.se (Jan D.)
  4. Subject: Update FAQ? Was: fast way to get number of elements in an assoc array?
  5. Message-ID: <1992Aug28.075021.21372@irfu.se>
  6. Date: Fri, 28 Aug 1992 07:50:21 GMT
  7. References: <1992Aug27.032106.20515@CS.ORST.EDU> <BtnIDn.390@news.cso.uiuc.edu>
  8. Organization: Swedish Institute of Space Physics, Uppsala, Sweden
  9. Keywords: associative array number count $#array $#
  10. Lines: 39
  11.  
  12. In article <BtnIDn.390@news.cso.uiuc.edu> ejk@ux2.cso.uiuc.edu (Ed Kubaitis - CCSO) writes:
  13. >jacobsd@prism.cs.orst.edu (Dana Jacobsen) writes:
  14. >  |
  15. >  |  Is there a function akin to $#array that works on associative arrays? I
  16. >  |have an associative array with over 30,000 keys, and this is what I'm 
  17. >  |currently doing:
  18. >  |
  19. >  |    @dummykey = keys(%records);
  20. >  |    print $#dummykey+1, " records loaded.\n";
  21. >  |    undef (@dummykey);
  22. >  |
  23. >  |  The problem with this is that the key list takes up a significant chunk of
  24. >  |memory, as well as being very slow.  The alternative way of handling this is
  25. >  |to keep a seperate variable that contains the number of elements in the 
  26. >  |array...
  27. >
  28. >From perl 4.0 patch #20: 
  29. >
  30. >  |Subject: scalar keys %array now counts keys for you
  31. >
  32. >So 'scalar(keys(%records))' or '$nkeys = keys(%records);' should work on 
  33. >perl beyond 4.019. Don't know how fast it is on large arrays, though.
  34. >
  35.  
  36. Hmm, looking at the source, it looks as if this is the way to go.
  37. keys(%records) in scalar context (or values(%records) for that matter)
  38. does NOT make a temporary array and then returns the length of the array (which
  39. I thought it did).
  40. It just counts the entries in %records. I can't imagine anything being faster.
  41.  
  42. This feature isn't mentioned in the manpage though.
  43.  
  44. So '$nkeys = keys(%records);' is the way to go.
  45.  
  46. Maybe update FAQ on this (if not already done)?
  47.  
  48.     Jan D.
  49.  
  50.  
  51.