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.
}
有帮助吗?

解决方案 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.

其他提示

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;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top