If you have a list in memory already, the straightforward and usually sufficient way to process it is a simple foreach
loop:
foreach my $item (@items) {
...
}
This is fine e.g. for the common case of doing some processing on $item
and then writing it out to a file without keeping the data around. However, if you build up some other data structure from the items, a while
loop is more memory efficient:
my @result;
while(@items) {
my $item = shift @items;
push @result, process_item($item);
}
Unless a reference to $item
directly ends up in your result list, items you shifted off the @items
array can be freed and the memory reused by the interpreter when you enter the next loop iteration.