Counting array elements in Perl

前端 未结 6 1542
逝去的感伤
逝去的感伤 2021-02-02 09:29

How do I get the total items in an array, NOT the last id?

None of two ways I found to do this works:

my @a;
# Add some elements (no consecutive ids)
$a[         


        
6条回答
  •  梦毁少年i
    2021-02-02 09:53

    It sounds like you want a sparse array. A normal array would have 24 items in it, but a sparse array would have 3. In Perl we emulate sparse arrays with hashes:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my %sparse;
    
    @sparse{0, 5, 23} = (1 .. 3);
    
    print "there are ", scalar keys %sparse, " items in the sparse array\n",
        map { "\t$sparse{$_}\n" } sort { $a <=> $b } keys %sparse;
    

    The keys function in scalar context will return the number of items in the sparse array. The only downside to using a hash to emulate a sparse array is that you must sort the keys before iterating over them if their order is important.

    You must also remember to use the delete function to remove items from the sparse array (just setting their value to undef is not enough).

提交回复
热议问题