I was trying to join elements of a Perl array.
@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]";
?
I was trying to join elements of a Perl array.
@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]";
?
Perhaps:
{
local $" = "][";
my @array = qw/a b c d e/;
print "[@array]";
}
Although you should probably just:
print "[" . join("][", @array) . "]";
Happy coding :-)
#!/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 };
}
Here are two options:
#!/usr/bin/perl
use strict;
use warnings;
my @array = 'a' .. 'e';
my $string = join('', map { "[$_]" } @array);
my $string1 = '[' . join('][', @array) . ']';
Another way to do it, using sprintf
.
my $str = sprintf '[%s]' x @array, @array;