### Number of elements in array

by Freezer (Sexton)
 on Sep 24, 2012 at 13:35 UTC Need Help??
Freezer has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

```
while(my @row_A_count_A_Ref_vs_Comp_B = \$sth_Count_Ref_vs_Comp_B
+->fetchrow_array()) {

I really want to know what the number of elements in  @row_A_count_A_Ref_vs_Comp_B is. I have tried the obvious, however I get strange numbers back. I think the problems lie in how the array is filled. Suggestion for lines on investigation welcomed.

Replies are listed 'Best First'.
Re: Number of elements in array
by blue_cowdawg (Monsignor) on Sep 24, 2012 at 13:57 UTC
Suggestion for lines on investigation welcomed

OH Chilly Monk,
If I want to know the number of elements in an array I'd try one of two things:

```#  assume two arrays with a number of elements
#   @rray1 & @rray2

my \$elements_1 = scalar @rray1;
#  or
my \$elements_2 = \$#rray2 + 1;

Either of the two will work.

Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
Re: Number of elements in array
by Corion (Pope) on Sep 24, 2012 at 13:48 UTC

What is "the obvious", and what strange numbers did you get?

Re: Number of elements in array
by NetWallah (Abbot) on Sep 24, 2012 at 13:55 UTC
If you want to get the number of rows in a database table, the most efficient way would be to let the database count them:
```  ...prepare ("Select COUNT(*) FROM TABLE_OR_QUERY");
# TABLE_OR_QUERY can be another (SELECT...) statement
Most databases will optimize queries, so you can do the count query, then do the data query as 2 separate queries.

I hope life isn't a big joke, because I don't get it.
-SNL

This counts the number of rows. The OP was counting the number of columns.

Of course, it's possible that the OP did actually want the number of rows...

perl -E'sub Monkey::do{say\$_,for@_,do{(\$monkey=[caller(0)]->[3])=~s{::}{ }and\$monkey}}"Monkey say"->Monkey::do'
Re: Number of elements in array
by Anonymous Monk on Sep 24, 2012 at 13:43 UTC

I have tried the obvious, however I get strange numbers back.

Such as?

Suggestion for lines on investigation welcomed.

trace, Dumper, the basics :)

Create A New User
Node Status?
node history
Node Type: perlquestion [id://995380]
Approved by Kenosis
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2017-08-21 11:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Who is your favorite scientist and why?

Results (322 votes). Check out past polls.

Notices?