Srivatsa Jenni
Srivatsa Jenni

Reputation: 39

Tracking of number of elements in an array iterated?

Is there any way that number of elements iterated in an for loop can be traced in perl: Like using special variables:

@arrayElements = (2,3,4,5,6,7,67);
foreach (@arrayElements) {
    # Do something
    # Want to know how may elements been iterated after 
    # some n number of elements processed without using another variable.
}

Upvotes: 1

Views: 117

Answers (3)

Futuregeek
Futuregeek

Reputation: 1980

You may get the number of elements in an array as

    my $num = @arrayElements;
    print $num;

OR

   my $num = scalar (@arrayElements);
   print $num;

OR

   my $num = $#arrayElements + 1;
   print $num;

And for finding number of elements iterated, we can use the below code :

my $count = 0;  #initially set the count to 0
foreach my $index(@arrayElements)
{
  $count++;
}
print $count;

Upvotes: 0

amon
amon

Reputation: 57590

In perl5 v12 and later, you can use the each iterator:

while(my($index, $element) = each @array_elements) {
  ...;
}

However, the more portable solution is to iterate over the indices, and manually access the element, as shown by ysth.

In any case, the number of elements that were visited (including the current element) is $index + 1.

Upvotes: 3

ysth
ysth

Reputation: 98388

Either just count as you go:

my $processed = 0;
foreach my $element (@array_elements) {
    ...
    ++$processed;
}

or iterate over the indexes instead:

foreach my $index (0..$#array_elements) {
    my $element = $array_elements[$index];
    ...
}

Upvotes: 7

Related Questions