my @children = $category->children; for my $i (0..$#children) { my $subcat = $children[$i]; my $is_last = $i == $#children; # More code here. }