home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / perl / 5546 < prev    next >
Encoding:
Text File  |  1992-08-27  |  2.2 KB  |  62 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: Re: fast way to get number of elements in an assoc array?
  5. Message-ID: <1992Aug27.153619.22643@irfu.se>
  6. Date: Thu, 27 Aug 1992 15:36:19 GMT
  7. References: <1992Aug27.032106.20515@CS.ORST.EDU> <MEISSNER.92Aug27103724@tiktok.osf.org>
  8. Organization: Swedish Institute of Space Physics, Uppsala, Sweden
  9. Lines: 51
  10.  
  11. In article <MEISSNER.92Aug27103724@tiktok.osf.org> meissner@osf.org (Michael Meissner) writes:
  12. >In article <1992Aug27.032106.20515@CS.ORST.EDU> jacobsd@prism.cs.orst.edu (Dana Jacobsen) writes:
  13. >
  14. >| 
  15. >|   Is there a function akin to $#array that works on associative arrays?
  16. >
  17. >    int (scalar (%array))
  18.  
  19. That can't be right, at least not on all machines. Consider this:
  20.  
  21. % perl -e 'print int(scalar (%ENV)), "\n"'
  22. 24
  23. % perl -e 'print int(scalar (keys %ENV)), "\n"'
  24. 39
  25. % env | wc -l
  26.      39
  27.  
  28.  
  29. BTW, int(scalar (keys %ENV)) isn't a good way to count elements for large
  30. assoc arrays.
  31.  
  32. This is a FAQ (but where's the FAQ? :-). Number 37 to be exact:
  33.  
  34. 37) How can I know how many entries are in an associative array?
  35.  
  36.     While the number of elements in a @foobar array is simply @foobar when
  37.     used in a scalar, you can't figure out how many elements are in an
  38.     associative array in an analogous fashion.  That's because %foobar in
  39.     a scalar context returns the ratio (as a string) of number of buckets
  40.     filled versus the number allocated.  For example, scalar(%ENV) might
  41.     return "20/32".  While perl could in theory keep a count, this would
  42.     break down on associative arrays that have been bound to dbm files.
  43.  
  44.     However, while you can't get a count this way, one thing you *can* use
  45.     it for is to determine whether there are any elements whatsoever in
  46.     the array, since "if (%table)" is guaranteed to be false if nothing
  47.     has ever been stored in it.  
  48.  
  49.     So you either have to keep your own count around and increments
  50.     it every time you store a new key in the array, or else do it
  51.     on the fly when you really care, perhaps like this:
  52.  
  53.     $count++ while each %ENV;
  54.  
  55.     This preceding method will be faster than extracting the
  56.     keys into a temporary array to count them.
  57.  
  58.  
  59.  
  60.     Jan D.
  61.  
  62.