在Perl中,如何在括号中包含每个元素之后连接数组的元素?

时间:2022-02-01 07:32:25

I was trying to join elements of a Perl array.

我试图加入Perl数组的元素。

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

will give me

会给我的

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

Is there anyway I can quickly get

无论如何,我可以很快得到

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

?

4 个解决方案

#1


24  

Another way to do it, using sprintf.

使用sprintf的另一种方法。

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

#2


13  

Here are two options:

这有两个选择:

#!/usr/bin/perl

use strict;
use warnings;

my @array = 'a' .. 'e';
my $string = join('', map { "[$_]" } @array);
my $string1 = '[' . join('][', @array) . ']';

#3


3  

#!/usr/bin/perl
use strict; use warnings;

local $" = '';
my $x = qq|@{[ map "[$_]", qw(a b c d e) ]}|;

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 };
}

#4


2  

Perhaps:

{
  local $" = "][";
  my @array = qw/a b c d e/;
  print "[@array]";
}

Although you should probably just:

虽然你应该只是:

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

Happy coding :-)

快乐的编码:-)

#1


24  

Another way to do it, using sprintf.

使用sprintf的另一种方法。

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

#2


13  

Here are two options:

这有两个选择:

#!/usr/bin/perl

use strict;
use warnings;

my @array = 'a' .. 'e';
my $string = join('', map { "[$_]" } @array);
my $string1 = '[' . join('][', @array) . ']';

#3


3  

#!/usr/bin/perl
use strict; use warnings;

local $" = '';
my $x = qq|@{[ map "[$_]", qw(a b c d e) ]}|;

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 };
}

#4


2  

Perhaps:

{
  local $" = "][";
  my @array = qw/a b c d e/;
  print "[@array]";
}

Although you should probably just:

虽然你应该只是:

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

Happy coding :-)

快乐的编码:-)