my $counter = 0; while(...) { print ",\n" if $counter; $counter++; ... # and the rest ... }