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

?

Answers


Another way to do it, using sprintf.

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

Here are two options:

#!/usr/bin/perl

use strict;
use warnings;

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

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

Need Your Help

Authentication using Facebook at first and then Google causes an error in Firebase for Android

android firebase facebook-login firebase-authentication google-authentication

As I understand from the Firebase Docs, if a user authenticates his account with a credential, he should strictly login by using the same credential if the credential is not linked with another one...

Dynamically add version number to dest output files w/ grunt

javascript node.js gruntjs

I have a package.json file with our version number, such as: