Algorithm for joining e.g. an array of strings

后端 未结 16 1768
陌清茗
陌清茗 2021-01-01 21:40

I have wondered for some time, what a nice, clean solution for joining an array of strings might look like. Example: I have [\"Alpha\", \"Beta\", \"Gamma\"] and want to join

16条回答
  •  醉梦人生
    2021-01-01 22:15

    join() in Perl:

    use List::Util qw(reduce);
    
    sub mjoin($@) {$sep = shift; reduce {$a.$sep.$b} @_ or ''}
    
    say mjoin(', ', qw(Alpha Beta Gamma));
    # Alpha, Beta, Gamma
    

    Or without reduce:

     sub mjoin($@) 
     {
       my ($sep, $sum) = (shift, shift); 
       $sum .= $sep.$_ for (@_); 
       $sum or ''
     }
    

提交回复
热议问题