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]";
?
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.
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.
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.
$#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.
Another way to do it, using sprintf
.
my $str = sprintf '[%s]' x @array, @array;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With