Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!samsung!uakari.primate.wisc.edu!ra!emory!mephisto!mcnc!thorin!oscar.cs.unc.edu!tell From: tell@oscar.cs.unc.edu Newsgroups: comp.lang.perl Subject: #elements in assoc array / array in scalar context Message-ID: <15429@thorin.cs.unc.edu> Date: 30 Jul 90 00:03:58 GMT Sender: news@thorin.cs.unc.edu Reply-To: tell@oscar.cs.unc.edu () Organization: University Of North Carolina, Chapel Hill Lines: 71 What is the recommended way to find out how many elements are in an associative array? I don't see any method that looks particularly efficient. Here's some playing around I did on some real code: # DB<3> s read_libdata(289): $nvalues = keys(%needvalues); DB<3> s read_libdata(291): while($libfile = pop(@libfiles) && $nvalues) { DB<3> p $nvalues # # Hmmm. $nvalues isn't set to anything useful. How do we find how many # items we're looking for? # First he takes a stab in the dark: # DB<5> p $#keys(%needvalues) syntax error in file (eval) at line 1, next 2 tokens "$#keys(" DB<6> p $#(keys(%needvalues)) syntax error in file (eval) at line 1, next 2 tokens "$#(" # Then he remembers the manual page: # If you evaluate an array in a scalar context, it returns the # length of the array. The following is always true: # # @whatever == $#whatever - $[ + 1; # and tries to "force a scalar (or numeric) context" # DB<8> p keys(%needvalues) + 0 0 DB<9> p (keys(%needvalues)) + 0 0 DB<10> p 0+keys(%needvalues) 0 # # This works, but copying that big array around seems inefficient. # or is the optimizer that good? # DB<11> @foo = keys(%needvalues); print $#foo 5 # # Just make sure that our test data is really ther # DB<12> p join(';', keys(%needvalues)) CRYSTAL;74LS04;74HCT573;74LS08;8052;LED So, how about making keys(%foo) return the number of elements in foo if evaluated in a scalar context? What does it produce in this context now? If I'm missing somthing, (and I probably am) please let me know. $Header: perly.c,v 3.0.1.5 90/03/27 16:20:57 lwall Locked $ Patch level: 18 Copyright (c) 1989, 1990, Larry Wall Perl may be copied only under the terms of the GNU General Public License, a copy of which can be found with the Perl 3.0 distribution kit. -------------------------------------------------------------------- Steve Tell e-mail: tell@wsmail.cs.unc.edu usmail: #5L Estes Park apts CS Grad Student, UNC Chapel Hill. Carrboro NC 27510 Former chief engineer, Duke Union Community Television, Durham, NC.