Perl字符串基本操作详解
http://developer.51cto.com/art/201007/211543.htm ◆Perl字符串中length取串长(字符数量) </pre><p><pre name="code" class="html">#!/usr/bin/Perl $str="abCD99e"; $strlen=length($str); print$strlen,"n"; [macg@localhostPerltest]$./tip.pl 7 ◆substr串,位置,长度-------取子串,注意从0开始数位置 <pre name="code" class="html">#!/usr/bin/Perl $str="ABCDEFG1234567"; $a=substr$str,5; print$a,"n"; [macg@localhostPerltest]$./tip.pl ABCDE $a=substr$str,-4,2; 从倒数第4个开始,取两个字符 [macg@localhostPerltest]$./tip.pl 45
<pre name="code" class="html">#!/usr/bin/Perl $str="ABCDEFG1234567"; $a="12"; $pos=index($str,$a); print$pos,"n"; [macg@localhostPerltest]$./tip.pl 7 @数组=split(pattern,串)将Perl字符串用某模式分成多个单词 <pre name="code" class="html">#!/usr/bin/Perl $str="ABCDEiFG12i34567"; @array=split(//,$str);按空格分 foreach(@array){ print$_,"n"; } [macg@localhostPerltest]$./tip.pl ABCDEi FG12i 345 6 7 @array=split(/+/,$line);当一行中各单词间的空格多于一个时
[macg@localhostPerltest]$vitip.pl #!/usr/bin/Perl $str="ABCDEiFG12i34567"; @array=split(/t/,$str); foreach(@array){ print$_,"n"; } [macg@localhostPerltest]$./tip.pl ABCDEiFG12i 34567 只分了两份,为什么? 因为同时满足TAB和空格的只有一处 所以必须加[] @array=split(/[t]/,$str);现在才是真正的按空格和TAB分 [macg@localhostPerltest]$./tip.pl ABCDEi FG12i 345 6 7 但还是有缺陷,TAB和空格相连时,TAB被认为是空格划分的子串,或者空格被认为是TAB划分的子串
语法:join($string,@array) ? 本文和大家重点讨论一下Perl字符串的一些基本操作,比如Perl字符串数组元素赋值:@tmp=qw(aaabbbkkk9000);相当于@tmp=(“aaa”,“bbb”,“kkk”,“9000)。至于其他操作请看本文详细介绍。 Perl字符串操作 Perl字符串数组元素赋值:@tmp=qw(aaabbbkkk9000);相当于@tmp=(“aaa”,“9000); ◆Perl字符串比较,绝不能用==,要用eq [macg@localhostPerltest]$vitip.pl #!/usr/bin/Perl print"input:"; while(chomp($input=<>)){ print"yourinputis$inputn"; if($input=="q"){print"chooseqn";last;} elsif($input=='n'){print"inputis$inputn";next;} else{print"inputok,tryagainn";} print"input:"; } [macg@localhostPerltest]$./tip.pl input:x yourinputisx chooseq ◆Perl字符串用==是最常犯的错误 即使是整形,也尽量用eq,少用== Argument""isn'tnumericinnumericeq(==)at./address.plline77,<STDIN>line2. 正确的做法是:不论整形Perl字符串,都用eq
运算符,常用于输出 .运算符和,类似也是Perl字符串相加但,通常只用于print而.可以用在任何Perl字符串相加的地方 x运算符号
因为可能+就是真加了(数字相加),而不是Perl字符串合并 $v1=99; $v2='121'; print$v1+$v2; $v1=99; $v2='121'; print$v2.$v1; 220 12199 ◆Perl字符串的连接可以连接整形和字符形,整形也被当作字符型处理,没有printf里的%d问题 $date="date"."0".$min;????????????????????? # use "." to joint string [root@ntrackermac]#./tip.pl
$str="abCD99e"; $str=uc($str); $str="abCD99e"; $str=lc($str); [macg@localhostPerltest]$./tip.pl ABCD99E [macg@localhostPerltest]$./tip.pl abcd99e (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |