In this paper, we focus on the use of the Perl split function, a very useful function in Perl is the Perl split function-splitting the string and putting the segmented result into the array. This Perl split function uses the regular expression (RE) and works on the $_ variable if it is not specific.
Perl Split function
A very useful function in Perl is the Perl split function-splitting the string and putting the segmented result into the array. This Perl split function uses the regular expression (RE) and works on the $_ variable if it is not specific.
The Perl split function can be used like this:
- $info="caine:michael:actor:14,leafydrive";
- @personal=split (/:/, $info);
The result is: @personal = ("Caine", "Michael", "Actor", "14,leafydrive");
If we have stored the information in the $_ variable, we can do this:
@personal =split (/:/);
If each field is delimited by any number of colons, it can be split with the RE code:
- $_="Capes:geoff::shotputter:::bigavenue";
- @personal=split (/:+/);
The result is: @personal = ("Capes", "Geoff", "Shotputter", "bigavenue");
But the following code:
- $_="Capes:geoff::shotputter:::bigavenue";
- @personal=split (/:/);
The result is: @personal = ("Capes", "Geoff", "" "," Shotputter "," "," "", "bigavenue");
In this Perl split function, words can be split into characters, sentences can be divided into words, and paragraphs can be divided into sentences:
- @chars=split (//, $word);
- @words=split (//, $sentence);
- @sentences=split (/\./, $paragraph);
In the first sentence, an empty string is matched between each character, so the @chars array is an array of characters. >>
The section between is the regular expression (or the separation rule) that the split uses
\s is a wildcard character that represents a space
+ represents repeating one or more times.
So, \s+ represents one or more spaces.
Split (/\s+/, $line) indicates that the string is $line, separated by a space.
For example, $line = "Hello friends Welcome to my blog 61dh.com";
Split (/\s+/, $line) is obtained after:
Hello Friend Welcome to visit my blog 61dh.com
Perl:split function Usage