foreach $field (param) { # Isolate non-empty values my @values = grep { ! /^\s*$/ } param($field); next unless @values; # Skip if nothing available # Establish a header line. Note that I added an "Other" class my $header = "Other:"; $header = "First:" if $field =~ /Data_One/; $header = "Second:" if $field eq /Second_Part/; # Print it all. $, is the output record separator for prints local $, = "\n"; print $header, @values, "\n"; }