PERL:仅在没有段落的数组循环(最后一次迭代循环)上处理元素时,才能进行进一步处理
我如何检查是否在数组中不存在foreach循环处理的元素?
示例:
my @array = ("abc","def","ghi");
foreach my $i (@array) {
print "I am inside array\n";
#####'Now, I want it further to go if there are no elements after
#####(or it can be said if it is the last element of array. Otherwise, go to next iteration'
print "i did this because there is no elements afterwards in array\n";
}
我可以想到做到这一点的方法,但是想知道我是否可以使用特定的关键字或函数以短暂的方式获得它。我想的一种方式:
my $index = 0;
while ($index < scalar @array) {
##Do my functionality here
}
if ($index == scalar @array) {
print "Proceed\n";
}
How can I check if no elements exist further in the array to be processed by the foreach loop?
Example:
my @array = ("abc","def","ghi");
foreach my $i (@array) {
print "I am inside array\n";
#####'Now, I want it further to go if there are no elements after
#####(or it can be said if it is the last element of array. Otherwise, go to next iteration'
print "i did this because there is no elements afterwards in array\n";
}
I could think of ways to do this, but wondering if I can get it in a short way, either using a specific keyword or function. One way I thought:
my $index = 0;
while ($index < scalar @array) {
##Do my functionality here
}
if ($index == scalar @array) {
print "Proceed\n";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有多种方法可以实现所需的结果,有些是基于数组的
$索引
的使用,而其他基于使用$#$#array-1
可以用于获得的方法Array Slice,带有$ array [-1]
的数组的最后一个元素。There are multiple ways to achieve desired result, some based on usage of
$index
of array, and other based on use$#array-1
which can be utilized to obtain the array slice, the last element of an array accessible with$array[-1]
.一种检测处理时间在最后一个元素时的一种方法
语法
$#array-name
用于数组中最后一个元素的索引。还请注意,每个 在数组上有用,如果有索引的用途
,请确保阅读文档要了解
每个
的微妙之处。One way to detect when processing is at the last element
The syntax
$#array-name
is for the index of the last element in the array.Note also that each works on arrays, useful if there are uses of indices
Then make sure to read docs to be aware of subtleties of
each
.取决于您要处理空数组的方式:
或
Depending on how you want to handle empty arrays:
or