perl的一些函数(一)
1. index 函数
index 主要用于字符串查找,返回从左->右查到子字符串的起始位置(起始位置0) ,可以带括号,也可以不带。当找不到会返回-1
使用方法:
index STR,SUBSTR,POSITION
index STR,SUBSTR
实例:
#!/usr/bin/perl
use strict;
my $str1="Love me, love my dog\n";
print "return the first child string location\n";
print index $str1,"ove";
print "\nreturn the first child string from start postition\n";
print index($str1,"ove",2);
print "\nif can't find return -1\n";
print index($str1,"LOVE");
print "\n";
结果:
D:\>perl index.pl
return the first child string location 查找ove, ove 总共有出现第一次出现1,第二次10
1
return the first child string from start postition
10 <-----------从第3个位置查找(L-0,o-1,v-2)
if can't find return -1
-1
2.rindex从后向前查找,使用方法和index一样
rindex STR,SUBSTR,POSITION
rindex STR,SUBSTR

#!/usr/bin/perl use strict; my $str1="Love me, love my dog\n"; print "return the first child string location\n"; print rindex $str1,"ove"; print "\nreturn the first child string from start postition\n"; print rindex($str1,"ove",4); print "\nif can't find return -1\n"; print rindex($str1,"LOVE"); print "\n";
运行结果:
D:\>perl rindex.pl
return the first child string location
10
return the first child string from start postition
1
if can't find return -1
-1
2.printf 函数
printf FILEHANDLE FORMAT, LIST
printf FILEHANDLE
printf FORMAT, LIST
printf 是从C语言移植过来的,参数和使用方法与C语言一样;
%表示域说明的开始,域标识符有以下
1 2 3 4 5 6 7 8 9 10 | #!/usr/bin/perl use strict; my $float_number = "10.789" ; printf ( "%.2f\n" , $float_number ); printf ( "%c\n" ,65); printf ( "%10s\n" , "this is a test,ten characters" ); printf ( "%-30s\n" , "Love perl" ); printf ( "%30s\n" , "Love perl" ); printf ( "%d\n" ,102.88); printf ( "%o\n" ,10); |
与类型 | 含义 |
d | 输出整形 |
s | 输出字符串 |
f | 输出浮点数 |
c |
字符 |
%.2f 保留2位小数,四舍五入
%10 s靠右对齐,10个字符字
结果:
D:\>perl printf.pl
10.79
A
this is a test,ten characters
Love perl
Love perl
102
12 # %o 将数字转换为八进制

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义