前言
本文主要记录一下,perl中的字符串函数。
- index 函数
- rindex 函数
- substr 函数
- sprintf 函数
13 字符串函数
#==================================
# index 函数从左往右查找子字符串
#==================================
# index函数返回查找到的字符串的位置
my $stuff = "Hello world!";
my $where = index($stuff, "wor");
print $where . "\n"; # 6
# index函数优先查找从左往右第一个
my $where1 = index($stuff, "o");
print $where1 . "\n"; # 4
# index函数查找第二个
my $where2 = index($stuff, "o", $where1+1);
print $where2 . "\n"; # 7
# index函数没找到就返回-1
my $where3 = index($stuff, "o", $where2+1);
print $where3 . "\n"; # -1 ,没找到
#==================================
# rindex 函数从右往左查找子字符串
# 返回的参数还是从左往右数
#==================================
# rindex函数从右往左进行查找,返回的参数还是从左往右数
my $name = "abc/123/xyz/hello";
$where1 = rindex($name, "/");
print $where1 . "\n"; # 11
# rindex函数从右往左进行查找第二个
$where2 = rindex($name, "/", $where1-1);
print $where2 . "\n"; # 7
#==================================
# substr 函数长字符串中提取子字符串
#==================================
#substr函数从第8个字符开始提取,提取长度5
my $a = substr("Fred J. Flintstone", 8, 5);
print $a . "\n"; # Flint
#不够100,有多长提取多长
my $b = substr "Fred J. Flintstone", 13, 100;
print $b . "\n"; # stone
#省略第二个参数,直接提取到末尾
my $c = substr "Fred J. Flintstone", 13;
print $c . "\n"; # stone
#负数表示从右往左开始数
my $out = substr("some very long string", -3, 2);
print $out . "\n"; # in
# substr 和 index函数的结合使用
my $str = "some very long string";
my $r = substr($str, index($str, "l"));
print $r . "\n"; # long string
# substr的替换功能
my $string = "Hello world!";
substr($string, 0, 5) = "Goodbye";
print $string . "\n"; # Goodbye world!
# substr的整体替换功能,后边20个字符串进行替换
$string = "aaaaaaaa bbbbbbb ccccc fred ... fred ... fred ...";
substr($string, -20) =~ s/fred/barney/g;
print $string . "\n"; #aaaaaaaa bbbbbbb ccccc fred ... barney ... barney ...
#==================================
# sprintf 函数将一定格式的字符串保存在变量里边
#==================================
my $now = localtime;
print $now . "\n"; # Tue Jun 28 16:19:47 2022
my($sec, $min, $hour, $day, $mon, $year, $wday, $yday, $isdst) = localtime;
my $now_time = $year+1900 . "/" . ($mon+1) . "/" . $day . " " . $hour . ":" . $min . ":" . $sec;
print $now_time . "\n"; # 2022/6/28 16:25:59
my $now_time1 = sprintf("%4d/%02d/%02d %2d:%02d:%02d", $year+1900, $mon+1, $day, $hour, $min, $sec);
print $now_time1 . "\n"; #2022/06/28 16:39:17