Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

perl
string
array
split()
communitycreator

How to transform strings to arrays in Perl using split() method

okwudili onyejiaku

Overview

We can transform a string to an array in Perl the split() method. It only takes two parameters to start the transformation.

Syntax

split(at, str)

Parameters

at: This specifies where to start the transformation.

str: This is the string we want to transform to an array.

Return value

The value returned is an array.

Example

# create some strings
$name = "Okwudili Onyejiaku";
$quote = "Edpresso-is-great!";

# transform strings to array
@arr1 = split(" ", $name);
@arr2 = split("-", $quote);

# print results for @arr1
print "First Array:\n\n";
for (my $index = 0; $index <= $#arr1; $index++) {
  print("Element $index is $arr1[$index]\n");
}
# print results for @arr2
print "\nSecond Array:\n\n";
for (my $index = 0; $index <= $#arr2; $index++) {
  print("Element $index is $arr2[$index]\n");
}
Transfrom a string to an array in Perl

Explanation

  • Lines 2–3: We create two strings that we want to transform.
  • Line 6: We transform the string $name to an array at space (" ") and store the result in array @arr1.
  • Line 7: We transform the string $quote to an array at hyphen ("-") and store the result in array @arr2.

RELATED TAGS

perl
string
array
split()
communitycreator
RELATED COURSES

View all Courses

Keep Exploring