6.1 Split

With the function split you can split a string in smaller parts ('fields'). It returns a list or scalar, dependent of its context. I prefer a regex expression as first argument (one exception). A few examples.

Example 1:


$str = "a:b:c";
@arr = split(/:/, $str);
print("@arr"); # output: a b c
Example 2:

$str = "a:b:c";
($first, $second, $third) = split(/:/, $str);
print("\U$first $second $third\E"); # output: A B C
Example 3:

$str = "a:b:c:d:e";
($first, $second, @rest) = split(/:/, $str);
print("\U$first $second\E" . " and the rest: @rest"); # A B and the rest: c d e
Example 4:
Using a list slice:

$str = "a:b:c";
$last = (split(/:/, $str))[2];
print("$last"); # output: c 
Example 5:

$str = "abbc";
@arr = split(/bb/, $str);
print("@arr"); # output: a c 
Example 6:
A limit option can be added to set the maximum number of fields in the output:

$str = "a:b:c:d:e:f";
@arr = split(/:/, $str, 3);
print("@arr"); # 3 fields output: a b c:d:e;f 
Example 7:

$str = "abc";
@arr = split(//, $str, 2);
print("@arr");# 2 fields output: a bc 
Example 8:
The (clever) exception, I referred to:

$str = "  a    b        c      ";
@arr = split(" ", $str);
print("@arr");# output: a b c 
With /\s+/ an empty leading space is preserved, i.e. $arr[0] is empty.

Example 9:
Split without delimiter:

@arr = split(//, "abc");
print("@arr");# output: a b c 
Example 10:
Split with multiple delimiters (same type):

@arr=split(/-+/,"a-b--c---d");
print("@arr");# output: a b c d 
Example 11:
Split with multiple delimiters (different type):

@arr=split(/,\s*|\s+/,"a b   c 1, 2, 3");
print("@arr");# output: a b c 1 2 3 
Example 12:
Split with delimiters as empty strings:

@arr=split(/,/,"1,,,4");
print("@arr, length: "  . scalar(@arr));# output: 1   4, length: 4 
Last but not least, two examples on alternation and grouping:

Example 13:

$str = "a-b,c";
@arr = split(/-|,/, $str, 3);
print("@arr");# output: a b c
Example 14:

$str = "a-b,c";
@arr = split(/(-|,)/, $str, 3);
print("@arr"); # output: a - b , c
Each separator (here: - or ,) gets his own field.