Tuesday, 11 March 2014

Transformation of Array



Transform Strings to Arrays

Let's look into one more function called split(), which has the following syntax:
split [ PATTERN [ , EXPR [, LIMIT ] ] ]
This function splits a string into an array of strings, and returns it. If LIMIT is specified, splits into at most that number of fields. If PATTERN is omitted, splits on white space. Following is the example:
#! /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);
 
print "$string[3]\n";  # This will print Roses
print "$names[4]\n";   # This will print Michael

Transform Arrays to Strings

We can use the join() function to rejoin the array elements and form one long scalar string. This function has following 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:
#! /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";
This will produce following result:
Rain-Drops-On-Roses-And-Whiskers-On-Kittens
Larry, David, Roger, Ken, Michael, Tom

No comments: