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:
Example 2:$str = "a:b:c"; @arr = split(/:/, $str); print("@arr"); # output: a b c
Example 3:$str = "a:b:c"; ($first, $second, $third) = split(/:/, $str); print("\U$first $second $third\E"); # output: A B C
Example 4:$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 5:$str = "a:b:c"; $last = (split(/:/, $str))[2]; print("$last"); # output: c
Example 6:$str = "abbc"; @arr = split(/bb/, $str); print("@arr"); # output: a c
Example 7:$str = "a:b:c:d:e:f"; @arr = split(/:/, $str, 3); print("@arr"); # 3 fields output: a b c:d:e;f
Example 8:$str = "abc"; @arr = split(//, $str, 2); print("@arr"); # 2 fields output: a bc
With /\s+/ an empty leading space is preserved, i.e. $arr[0] is empty.$str = " a b c "; @arr = split(" ", $str); print("@arr"); # output: a b c
Example 10:@arr = split(//, "abc"); print("@arr"); # output: a b c
Example 11:@arr=split(/-+/,"a-b--c---d"); print("@arr"); # output: a b c d
Example 12:@arr=split(/,\s*|\s+/,"a b c 1, 2, 3"); print("@arr"); # output: a b c 1 2 3
Last but not least, two examples on alternation and grouping:@arr=split(/,/,"1,,,4"); print("@arr, length: " . scalar(@arr)); # output: 1 4, length: 4
Example 14:$str = "a-b,c"; @arr = split(/-|,/, $str, 3); print("@arr"); # output: a b c
Each separator (here: - or ,) gets his own field.$str = "a-b,c"; @arr = split(/(-|,)/, $str, 3); print("@arr"); # output: a - b , c