Saturday, April 26, 2008

Perl: convert character array to string

Share at Facebook

Previously I have posted a topic related to convert a string into character array into Perl here perl-string-to-character-array

I have found people are searching my blog to find the other way. I mean they have the character array, now they want to convert it into string back. Here is the example to do such things.
use strict;

## Convert String into array
my $str = " Perl: convert character array to string ";
my @char_array = split(//,$str);

## Make string from each value of char separated by string
$str = "@char_array";
print "$str\n";
## Replace the Extra separating spaces with blank
$str =~ s/(.)\s/$1/seg; ## Simple Regex
print "$str\n";
When the above code will execute, below will happen
Array to string with separated by space.
P e r l : c o n v e r t c h a r a c t e r a r r a y t o s t r i n g
Now squeeze the extra spaces will make above string into.
Perl: convert character array to string
Hope this little explanation will help you guys.


Anonymous said...

How about:

$str = join('',@char_array);

No interpolation/substitution required.

Alexander said...

# not to be a prude,
# but there are some typos.
# this is a fixed up version.

my ($str) = join "",@char_array;