because I generate each accession number first, for each accession number, I use foreach loop to generate item1 and item2, maybe some of the accession number have a couple of groups item1 and item2, maybe some of them have none item1 and item2 at all. I tried to use:
printf ("%08d",$accession);#which is before foreach loop.
Use a temporary variable. Set it to the value to print before entering the loop. After the first print in the loop, set it to an empty string. This assumes that the loop will produce at least one line of output.