Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

perl

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

?

like image 336
Jean Avatar asked Oct 28 '10 23:10

Jean


People also ask

How do I join an array element in Perl?

Perl Array join() FunctionThe Perl programming language join() function is used to connect all the elements of a specific list or array into a single string using a specified joining expression. The list is concatenated into one string with the specified joining element contained between each item.

How do you join array items?

Array.prototype.join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

What does Splice do in Perl?

In Perl, the splice() function is used to remove and return a certain number of elements from an array. A list of elements can be inserted in place of the removed elements.

What is $# in Perl?

$#array is the subscript of the last element of the array (which is one less than the length of the array, since arrays start from zero). Assigning to $#array changes the length of the array @array, hence you can destroy (or clear) all values of the array between the last element and the newly assigned position.


1 Answers

Another way to do it, using sprintf.

my $str = sprintf '[%s]' x @array, @array;
like image 191
FMc Avatar answered Nov 11 '22 20:11

FMc