use strict; use warnings; use Data::Dump 'pp'; my @words1 = ("", "", "abcd", "efgh", "", "", "jklm", "nopq", "", ""); my @words2 = ("", ",", "abcd", "efgh", "", "", "jklm", "nopq", ""); my @words3 = ("", "", "abcd", "efgh", "", "jklm", "nopq", "", "", "rstu", "vwxy", "", ""); print "Double blancs:\n"; my @combined1 = process(@words1); pp \@combined1; print "\nArray doesn't start or end with double blancs:\n"; my @combined2 = process(@words2); pp \@combined2; print "\nArray contains single blanc:\n"; my @combined3 = process(@words3); pp \@combined3; sub process { my @input = @_; my @output = (); my $buffer = undef; my $last = shift @input; # We take the first element for whatever it is while ( defined(my $this = shift @input) ) { if ($last eq "" and $this eq "") { # Double blancs # When we run into the first double blanc, # $buffer will be undef. # We don't want to push that. push @output, $buffer if defined $buffer; $buffer = ""; } elsif ($this ne "") { # Non-blanc string # ($buffer || "") to prevent "undefined value in concatenation" warning $buffer = ($buffer || "") . $this; } $last = $this; } return @output; }