In Perl, how can I join the elements of an array after including each element in brackets?

I tried to combine the elements of a Perl array.

@array=('a','b','c','d','e'); $string=join(']',@array); 

will give to me

 $string="a]b]c]d]e"; 

Anyway, I can quickly get

 $string="[a][b][c][d][e]"; 

?

+4
source share
4 answers

Another way to do this is using sprintf .

 my $str = sprintf '[%s]' x @array, @array; 
+21
source

Here are two options:

 #!/usr/bin/perl use strict; use warnings; my @array = 'a' .. 'e'; my $string = join('', map { "[$_]" } @array); my $string1 = '[' . join('][', @array) . ']'; 
+13
source
 #!/usr/bin/perl use strict; use warnings; local $" = ''; my $x = qq|@{[ map "[$_]", qw(abcde) ]}|; 

You can also generalize a little:

 #!/usr/bin/perl use strict; use warnings; my @array = 'a' .. 'e'; print decorate_join(make_decorator('[', ']'), \@array), "\n"; sub decorate_join { my ($decorator, $array) = @_; return join '' => map $decorator->($_), @$array; } sub make_decorator { my ($left, $right) = @_; return sub { sprintf "%s%s%s", $left, $_[0], $right }; } 
+3
source

May be:

 { local $" = "]["; my @array = qw/abcde/; print "[@array]"; } 

Although you should probably just:

 print "[" . join("][", @array) . "]"; 

Happy coding :-)

+2
source

All Articles