My assumption is that NateTut would like the custom join to behave analogously to the built-in join: two join-expressions must be present, and either may evaluate to the empty string; the list of strings to join may be empty.
AR's and kennethk's approaches both produce oddball output for corner cases: undefined or oddly joined output, operations on undefined values.
As far as I can tell, the following functions, in increasing order of opacity, all operate like the join built-in. I haven't done any Benchmark-ing on them.
sub join_multi {
die "not enough parameters for join_multi()" if @_ < 2;
my $delim1 = shift;
my $delim2 = shift;
return @_ > 1 ? join $delim1, $_[0], join $delim2, @_[1 .. $#_]
: @_ ? $_[0]
: ''
;
}
sub join_multi {
die "not enough parameters for join_multi()" if @_ < 2;
return @_ > 3 ? join $_[0], $_[2], join $_[1], @_[3 .. $#_]
: @_ == 3 ? $_[2]
: ''
;
}
sub join_multi {
die "not enough parameters for join_multi()" if @_ < 2;
return
join '',
map { ('', $_[0], ($_[1]) x ($#_ - 2))[$_ - 2], $_[$_] }
2 .. $#_
;
}
|