Perl substr () Function example, substr () function instance code-returns the substring of expr, starting with offset within the string.
Grammar:
Substr EXPR, OFFSET, LEN, replacement
Substr EXPR, OFFSET, LEN
Substr EXPR, OFFSET
Definitions and usage
Returns the substring of expr, beginning with offset within the string. If offset is negative, start with a string with a lot of character endings. If Len specifies, the number of bytes returned, or all the bytes, until the end of the string (if unspecified). If Len is a negative number, it ends up with a string of characters.
Replaces the replacement string if you replace the substring specified by replacement.
If you specify a substring that crosses the end of the string, returns the only valid element of the original string.
return value
String
Example
Try the following example:
#!/usr/bin/perl-w
#by www.yiibai.com
$temp = substr ("okay");
Print "Substring Valuye is $temp \ n";
$temp = substr ("Okay",,);
Print "Substring Valuye is $temp \ n";
This will produce the following results:
Substring Valuye is ay
Substring Valuye is Ka
Instance parsing Perl substr function application
This article focuses on the Perl substr function application, and when writing Perl programs, we sometimes need to intercept parts of a string, which is usually implemented using the SUBSTR function.
Perl substr Function Application
When writing Perl programs, we sometimes need to intercept parts of a string, which is usually implemented using the Perl substr function.
$str = "Testtest";
Printsubstr ($str, 0,5);
$str = "Testtest";
Run the above program, output the result "Testt", this is the result we want. Look at the following procedure:
$STR = "Test text";
Printsubstr ($STR, 0,1);
$STR = "Test text";
This is the output of a "?", which is obviously not the result we want. Because in Perl, all strings entered from the outside (including the strings written in the program) are treated as bytes, "Printsubstr ($str, 0, 1);" This sentence simply takes the first byte of the "Test text" and prints it out, whereas a single byte cannot represent a Chinese character, so it outputs "?".
If you want the above program to output the correct results, you need to use the Decode function to convert "Test text" into a Perl internal string, so that Perl treats "Test text" as a string, and then uses "substr ($STR, 0, 1);" The interception is not a byte, but a Chinese character.
Here's a look at the use of the Perl substr function:
directive: substr
Syntax: substr ($string, Offset,length)
Offset represents the position of the start character, length represents the string length of the reference, or the length of the last character from the starting value to the string if the omitted length. and
If offset is negative, the character is specified from the right of the string.
Example:
$s =substr ("perl5", 2,2); #这时 $s = "RL";
$s =substr ("perl5", 2); #这时 $s = "RL5";