Home > Enterprise >  Convert single element array to string with dot added before the string in Perl
Convert single element array to string with dot added before the string in Perl

Time:01-29

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

Please help.

Thanks in advance

CodePudding user response:

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 test.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.

  •  Tags:  
  • Related