my @b = list_reduce { push @$_, $b if !@$_ || $b ne $_->[-1]; undef } undef, @a; my @b = list_reduce { push @$_, $b if $a || $b ne $_->[-1]; 0 } 1, @a; my @b = list_reduce { push @$_, $b if defined($b) && $b ne $a; $b } undef, @a; my @b = list_reduce { push @$_, grep defined && $_ ne $a, $b; $b } undef, @a;