If you care about the position of elements in an array, you should simply iterate them by index instead of by element.
my @children = $category->children;
for my $i (0..$#children) {
my $subcat = $children[$i];
my $is_last = $i == $#children;
# More code here.
}
There is nothing particularly elegant or fancy about this solution. In fact, it's down right boring. However, it's very clear what purpose each variable serves. And so is very maintainable.
There are other abstractions that you could use that are more both elegant or obfuscated. One good way would be to use an Iterator class. However, this needlessly adds more dependencies to something that is honestly very basic, so I at least wouldn't bother.
- Miller