Transform Perl Arrays to Strings


We can use the join() function in Perl to rejoin the array elements and form one long scalar string. This function has the following syntax −

Syntax

join EXPR, LIST

This function joins the separate strings of LIST into a single string with fields separated by the value of EXPR and returns the string. Following is the example −

Example

 Live Demo

#!/usr/bin/perl
# define Strings
$var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$var_names = "Larry,David,Roger,Ken,Michael,Tom";

# transform above strings into arrays.
@string = split('-', $var_string);
@names = split(',', $var_names);

$string1 = join( '-', @string );
$string2 = join( ',', @names );

print "$string1\n";
print "$string2\n";

Output

This will produce the following result −

Rain-Drops-On-Roses-And-Whiskers-On-Kittens
Larry,David,Roger,Ken,Michael,Tom

Updated on: 29-Nov-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements