sub make_iterative (\@) { my $count = 0; my $arrayref = shift; return sub { return $count < @$arrayref ? undef : $arrayref->[$count++]; }; } my @files = get_files(); my $iter = make_iterative(@files); print xml_header(); while (my $el = $iter->()){ print Chunk2XML($el); } print xml_footer();