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[0]= '1';
$a[5]= '2';
$a[23]= '3';
print $#a, "\n"; # Prints 23
print scalar(@a), "\n"; # Prints 24
I expected to get 3...
@people = qw( bob john linda );
$n = @people; # the number 3
Print " le number in the list is $n \n";
Expressions in Perl always return the appropriate value for their context. For example, how about the “name” * of an array. In a list context, it gives the list of elements. But in a scalar context, it returns the number of elements in the array:
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).
Maybe you want a hash instead (or in addition). Arrays are an ordered set of elements; if you create $foo[23]
, you implicitly create $foo[0]
through $foo[22]
.
sub uniq {
return keys %{{ map { $_ => 1 } @_ }};
}
my @my_array = ("a","a","b","b","c");
#print join(" ", @my_array), "\n";
my $a = join(" ", uniq(@my_array));
my @b = split(/ /,$a);
my $count = $#b;
print scalar grep { defined $_ } @a;
Source: Stackoverflow.com