Perl split Function

The Perl split function splits a string into an array. A string is splitted based on delimiter specified by pattern. By default, it whitespace is assumed as delimiter.

split syntax is:

snippet
Split /pattern/, variableName

Perl split Example

In this example, split returns a list of strings. The delimiter is (-). It means string is splitted at (-).

snippet
my $str = "Cu-K-Na-Hg-Pb-Li";  
my @break = split /-/, $str;  
print "@break\n";

Output:

Output
Cu K Na Hg Pb Li

Perl split Limit number of parts

We can limit the number of parts to be splitted for a string.

In this example, string splits in 3 parts.

snippet
my $str = "Cu-K-Na-Hg-Pb-Li";  
my @break = split(/-/, $str, 3);  
print "@break\n";

Output:

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents