Split operator _php Tutorial

Source: Internet
Author: User
Split it splits the string according to the given pattern, and it is quite handy to decompose the extracted fields with this operator for strings that separate different fields with tabs, colons, whitespace characters, or any symbol. As long as you can write a delimiter into a pattern (usually a simple regular expression), you can decompose the data with split. Its usage is as follows: my @fields = split/separator/, $string; The split operator here scans the specified string with split mode and returns a list of fields (that is, substrings). This is the end of the current field, the beginning of the next field, as long as the pattern matches somewhere in a successful position. Therefore, the contents of any matching pattern do not appear in the return field. Here is a typical split pattern with a colon as a delimiter: my @fields = Split/:/, "Abc:def:g:h"; #得到 ("abc", "Def", "G", "H") if two separators are joined together, an empty field is generated: my @fields = Split/:/, "Abc:def::g:h"; #得到 ("abc", "Def", "", "G", "H") there is a rule here, which at first glance is odd, but rarely problematic: split retains the empty field at the beginning, but leaves the empty field at the end. For example: my @fields = Split/:/, "::: A:b:c:::"; #得到 ("," "," "", "a", "B", "C") using Split's/\s+/pattern to delimit characters based on whitespace is also a common practice. This mode takes all contiguous blanks as a single space and splits the data: my $some _input = "This is a \ t test.\n"; My @args = Split/\s+/, $some _input; #得到 ("This", "is", "a", "Test.") The default split separates strings in $_ with whitespace characters: my @fields = split; #等效于split/\s+/,$_; This is almost equal to the/\s+/pattern, except that it omits the empty field at the beginning. So, even if the line starts with a blank, you won't see an empty field at the beginning of the return list. If you want to break down a space-delimited string in this way, you can use a space as a pattern: Split ', $other _string use a space as a pattern is the special use of split. In general, the pattern used in split is as simple as it was seen before. But if you use more complex patterns, avoid using capture parentheses in the pattern, as this will start the so-called "delimiter retentionMode (see Perlfunc documentation for details). If you need to use grouping matching in a pattern, use the non-capturing parentheses (?:) notation in Split to avoid surprises. Further deepen the convenience of split decomposition extraction fields. Here's a piece of code that I'm actually working on that doesn't use the split operator to decompose the extracted fields (and then the code that uses the split operator) to get a sense of how powerful it is: task: Extracting the user name, user home directory information from the passwd file; Let's take a look at the record format in the passwd file (excerpt from Figure 1-1): root:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/bin/sh ... You can see that each field is delimited with a colon (:), with the first record from left to right as an example we want to extract the root (user name) before the first colon and the/root (user home directory) in front of the sixth colon. [PHP] #代码1.1 The field code is not extracted using the split operator; #!/usr/bin/perl-w use strict; Open (FH, '/etc/passwd ') or die "Can ' t Open file: $!"; while ( {My ($Pos, $endPos, $length, $Name, $Dir); ############# # take the user name ############# $length = index ($_, ":"); $Name = substr ($_, 0, $length); ##################### # Take user home directory location ##################### $endPos = Rindex ($_, ":"); # $endPos-1 Skips the current position (colon) $Pos = Rindex ($_, ":", $endPos-1); # $Pos + 1 Skips the current position (colon) # Find direction from left to right. So +1 $Pos + = 1; $length = $endPos-$Pos; $Dir = substr ($_, $Pos, $length); Print "$Name \t$dir\n"; } close (FH); After the program runs the output is as follows (Figure 1-2): Root/rootbin/bin ... Now let's analyze the algorithm of this code, extract the user name is very simple only need to find the first colon position through the substr ($_,0, $length) function to return the substring is the required user name. The complex part of the algorithm is to extract the user's home directory, the passwd file itself is a fixed format through Figure 1-1, the record from the back forward (right-to-left) after the second colon after the/root is the owner directory information. Extract the user home directory algorithm idea: 1, skip record the last field, 2, find the bottom of the second field starting position, 3, the beginning of the first field of the penultimate (colon) position minus the second-to-last field character starting position (/number), the result is the owner of the directory field of the character length; 4, substr ($_, $Pos, $length); Returns the user home directory information; 5. Complete. (Figure 1-3 Extract User directory algorithm) summary, through the Perl string processing function to locate, extract field information can complete our task, we can foresee when we want to extract multiple unconnected fields, the steps will be more cumbersome, the code is longer, also more error-prone, if the record each field position changes, You will have to redesign your algorithm. Now, let's look at the example of using the split operator to decompose the extracted fields: [PHP] #代码1.2 Use the split operator to extract the field code; #!/usr/bin/perl-w using Strict; Open (FH, ' etc/PASSWD ') or die "Can ' t Open file: $!"; while ( ) {########### # Fetch user Information ########### my ($Name, $Dir) = (split/:/,$_) [0,5]; print "$Name \t$dir\n";} close (FH);.

http://www.bkjia.com/phpjc/477706.html www.bkjia.com true http://www.bkjia.com/phpjc/477706.html techarticle split it splits the string according to the given pattern, and for a string that separates different fields using tabs, colons, whitespace characters, or any symbol, use this operator to decompose the extracted fields ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.