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 /pattern/, variableName
In this example, split returns a list of strings. The delimiter is (-). It means string is splitted at (-).
my $str = "Cu-K-Na-Hg-Pb-Li"; my @break = split /-/, $str; print "@break\n";
We can limit the number of parts to be splitted for a string.
In this example, string splits in 3 parts.
my $str = "Cu-K-Na-Hg-Pb-Li"; my @break = split(/-/, $str, 3); print "@break\n";
We can split a character at more than one delimiter. In the following example, we have split the string at (=) and (,).
As they are key-value pairs, we can assign the result into a hash instead of an array.
Split on empty string means the string will split at every place where it will find an empty string. There is an empty string, between every two characters. It means it will return the original string split into individual characters.
Perl join character, joins elements into a single string using a delimiter pattern to separate each element. It is opposite of split.
join 'pattern', variableName
In the following example, we have joined in three different ways.
First, we are joining (:) in between each elements of array.
Second, we will join (- vowels) with the output of first one.
Third, we added two more characters in the original array.