Transform Perl Strings into Arrays


Let's look into a Perl function called split(), which has the following syntax −

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 whitespace. 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);

print "$string[3]\n";    # This will print Roses
print "$names[4]\n";     # This will print Michael

Output

This will produce the following result −

Roses
Michael

Updated on: 29-Nov-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements