Domanda

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.
}
È stato utile?

Soluzione 2

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.

Altri suggerimenti

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];
    ...
}

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top