perl学习笔记(十三)字符串函数

本文详细介绍了Perl中的字符串处理函数,包括index、rindex、substr及sprintf等函数的使用方法与实例,帮助读者更好地掌握Perl语言。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

本文主要记录一下,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

总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值