home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.perl
- Path: sparky!uunet!mcsun!sunic!corax.udac.uu.se!irfu.se!jhd
- From: jhd@irfu.se (Jan D.)
- Subject: Re: fast way to get number of elements in an assoc array?
- Message-ID: <1992Aug27.153619.22643@irfu.se>
- Date: Thu, 27 Aug 1992 15:36:19 GMT
- References: <1992Aug27.032106.20515@CS.ORST.EDU> <MEISSNER.92Aug27103724@tiktok.osf.org>
- Organization: Swedish Institute of Space Physics, Uppsala, Sweden
- Lines: 51
-
- In article <MEISSNER.92Aug27103724@tiktok.osf.org> meissner@osf.org (Michael Meissner) writes:
- >In article <1992Aug27.032106.20515@CS.ORST.EDU> jacobsd@prism.cs.orst.edu (Dana Jacobsen) writes:
- >
- >|
- >| Is there a function akin to $#array that works on associative arrays?
- >
- > int (scalar (%array))
-
- That can't be right, at least not on all machines. Consider this:
-
- % perl -e 'print int(scalar (%ENV)), "\n"'
- 24
- % perl -e 'print int(scalar (keys %ENV)), "\n"'
- 39
- % env | wc -l
- 39
-
-
- BTW, int(scalar (keys %ENV)) isn't a good way to count elements for large
- assoc arrays.
-
- This is a FAQ (but where's the FAQ? :-). Number 37 to be exact:
-
- 37) How can I know how many entries are in an associative array?
-
- While the number of elements in a @foobar array is simply @foobar when
- used in a scalar, you can't figure out how many elements are in an
- associative array in an analogous fashion. That's because %foobar in
- a scalar context returns the ratio (as a string) of number of buckets
- filled versus the number allocated. For example, scalar(%ENV) might
- return "20/32". While perl could in theory keep a count, this would
- break down on associative arrays that have been bound to dbm files.
-
- However, while you can't get a count this way, one thing you *can* use
- it for is to determine whether there are any elements whatsoever in
- the array, since "if (%table)" is guaranteed to be false if nothing
- has ever been stored in it.
-
- So you either have to keep your own count around and increments
- it every time you store a new key in the array, or else do it
- on the fly when you really care, perhaps like this:
-
- $count++ while each %ENV;
-
- This preceding method will be faster than extracting the
- keys into a temporary array to count them.
-
-
-
- Jan D.
-
-