find the index of the substring in one string.
- $where = index($big, $small);
The index function will always report the location of the first found occurrence of the
substring.
we can use the third parameter to specify the begining index.
- my $stuff = "Howdy world!";
-
my $where1 = index($stuff, "w"); # $where1 gets 2
-
my $where2 = index($stuff, "w", $where1 + 1); # $where2 gets 6
-
my $where3 = index($stuff, "w", $where2 + 1); # $where3 gets -1 (not found)
if the substring can’t be found at that position or later, the return value will be −1.
- my $last_slash = rindex("/etc/passwd", "/"); # value is 4
substr EXPR,OFFSET,LENGTH,REPLACEMENT
substr EXPR,OFFSET,LENGTH
substr EXPR,OFFSET- $part = substr($string, $initial_position, $length);
It takes three arguments: a string value, a zero-based initial position (like the return
value of index), and a length for the substring. The return value is the substring:
- my $mineral = substr("Fred J. Flintstone", 8, 5); # gets "Flint"
-
my $rock = substr "Fred J. Flintstone", 13, 1000; # gets "stone"
- my $out = substr("some very long string", −3, 2); # $out gets "in"
An alternative to using substr() as an lvalue is to specify the
replacement string as the 4th argument. This allows you to replace
parts of the EXPR and return what was there before in one operation,
just as you can with splice().
- my $s = "The black cat climbed the green tree";
-
my $z = substr $s, 14, 7, "jumped from"; # climbed
-
# $s is now "The black cat jumped from the green tree"
- my $string = "Hello, world!";
-
substr($string, 0, 5) = "Goodbye";
- print $string;
-
-
Goodbye,
Note that the lvalue returned by the three-argument version of substr() acts as
a 'magic bullet'; each time it is assigned to, it remembers which part
of the original string is being modified; for example:
- $x = '1234';
-
for (substr($x,1,2)) {
-
$_ = 'a'; print $x,"\n"; # prints 1a4
-
$_ = 'xyz'; print $x,"\n"; # prints 1xyz4
-
$x = '56789';
-
$_ = 'pq'; print $x,"\n"; # prints 5pq9
-
}
The sprintf function takes the same arguments as printf (except for the optional
filehandle, of course), but it returns the requested string instead of printing it. This is
handy if you want to store a formatted string into a variable for later use, or if you want
more control over the result than printf alone would provide:
- my $date_tag = sprintf
-
"%4d/%02d/%02d %2d:%02d:%02d",
-
$yr, $mo, $da, $h, $m, $s;
$date_tag gets something like "2038/01/19 3:00:08".
The leading zero
on the format number means to use leading zeros as needed to make the number as
wide as requested. Without a leading zero in the formats, the resulting date-and-time
string would have unwanted leading spaces instead of zeros, like "2038/ 1/19 3: 0: 8"
阅读(855) | 评论(0) | 转发(0) |