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
#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
#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 :-)
快乐的编码:-)