Reputation: 169
I have an array which has one element
I am trying to convert that array element to a string with a dot added before the string
my $string = [ 'text' ];
my $convert_str = join(".", @$string);
print $convert_str;
The expected output should be
.text
I am getting the output without dot as just:
text
Upvotes: 1
Views: 707
Reputation: 183
I don't know Perl myself so sorry in advance if I got something wrong.
Using join would only "work" with arrays of 2 or more elements and the separator would be inserted in between the elements. For example
my $string = [ 'text', 'another' ];
my $convert_str = join(".", @$string);
print $convert_str;
would give the result text.another
If you only have 1 elements in the array and you want to prepend a dot before it then this could be done as follows
my $string = [ 'text' ];
my $convert_str = "." . $string->[0];
print $convert_str;
Here, I'm using $string->[0]
to access the first element of the array and .
to concatenate the dot and place it in front of the string.
Upvotes: 3
Reputation: 69314
The documentation for join()
says this:
join EXPR,LIST
Joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns that new string.
So you need to pass it a list of strings and it inserts the EXPR in between the elements of the list. You have a list with one item, so there's nowhere for the EXPR to go and your string is unchanged.
You can just prepend your dot by adding the dot to the string.
my $convert_str = ".$string->[0]";
print $convert_str;
Upvotes: 2