Jean
Jean

Reputation: 22675

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

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]";

?

Upvotes: 7

Views: 34381

Answers (4)

FMc
FMc

Reputation: 42411

Another way to do it, using sprintf.

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

Upvotes: 27

mscha
mscha

Reputation: 6830

Here are two options:

#!/usr/bin/perl

use strict;
use warnings;

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

Upvotes: 14

Sinan Ünür
Sinan Ünür

Reputation: 118118

#!/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 };
}

Upvotes: 4

user166390
user166390

Reputation:

Perhaps:

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

Although you should probably just:

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

Happy coding :-)

Upvotes: 4

Related Questions