Chinaunix首页 | 论坛 | 博客
  • 博客访问: 690839
  • 博文数量: 108
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 1436
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-31 09:49
文章分类
文章存档

2019年(16)

2015年(2)

2014年(20)

2013年(70)

我的朋友

分类: PERL

2014-01-22 15:24:48

一、历遍数组
[root@shangxiantongbu script]# cat shuzu3.pl
#!/usr/bin/perl
@lp=qw(chocolate dajiba dazar qiaotun lvyue);
for ($index=0;$index<@lp;$index++) {
  print "wo tama xihuan de shi $lp[$index] and ...\n"
}
print "many others.\n";
[root@shangxiantongbu script]# ./shuzu3.pl
wo tama xihuan de shi chocolate and ...
wo tama xihuan de shi dajiba and ...
wo tama xihuan de shi dazar and ...
wo tama xihuan de shi qiaotun and ...
wo tama xihuan de shi lvyue and ...
many others.
P e r l还有另一个循环语
句,称为f o r e a c h语句,我们在第3学时没有介绍。f o r e a c h语句设置一个索引变量,称为迭代器,
它相当于列表的每个元素。请看下面这个例子:


二、在数组与标量之间进行切换
将标量转换成数组的方法之一是使用 s p l i t函数。S p l i t函数
拥有一个模式和一个标量,并且使用该模式来分割该标量。第一个参数是该模式(这里用斜
杠括起来),第二个参数是要分割的标量:
@words=split(/  /.  "the quick brown fox");
还是举个例子吧
[root@shangxiantongbu script]# cat shuzu4.pl
#!/usr/bin/perl
while() {
   ($firstchar)=split(//,$_);
   print "the first char shi $firstchar\n";
}
[root@shangxiantongbu script]# ./shuzu4.pl
6666
the first char shi 6


[root@shangxiantongbu script]# cat shuzu4.pl
#!/usr/bin/perl
while() {
   ($firstchar)=split(/5555/,$_);
   print "the first char shi $firstchar\n";
}
[root@shangxiantongbu script]# ./shuzu4.pl
sdfsdfsdf55555
the first char shi sdfsdfsdf

/  /这两个里面就是要切割的标记而已啦

第一行用于读取来自终端的数据,每次读一行,并将 $ _设置为等于该行。第二行使用空
模式来分割$ _。S p l i t函数返回来自$ _中的这个行的每个字符的列表。该列表被赋予左边的列
表,而该列表的第一个元素则被赋予 $ f i r s t c h a r,其余均放弃。
s p l i t使用的模式实际上是一些正则表达式。正则表达式是一种复杂的模
式匹配语言,我们将在第 6学时介绍这方面的内容。而现在,我们的例子
将使用一些简单的模式,如空格、冒号、逗号等等。当你学习了正则表达
式的内容之后,我们将举例说明如何使用比较复杂的模式来用
s p l i t分割标量。

在这个例子中,$ m e s s a g e被s p l i t分割成一个列表。该列表被 j o i n函数使用,并用逗号重新
组合在一起。产生的结果是下面这个消息:
#!/usr/bin/perl
$lp ="love is here";
print "the string\"$lp\" consists of :\n",
        join('-',split(//,$lp));
[root@shangxiantongbu script]# ./shuzu5.pl
the string"love is here" consists of :
l-o-v-e- -i-s- -h-e-r-e

给数组重新排序
若要给数据
排序, P e r l提供了s o r t函数。S o r t函数将一个列表作为它的参数,并且大体上按照字母顺序对
列表进行排序,然后该函数返回一个排定顺序的新列表。原始数组保持不变,如下面这个例
子所示:
[root@localhost scripts]# cat shuzu1.pl
#!/usr/bin/perl
@chief=qw(Csdfsd Fsdfsdf Zdfghdh Adfhdf Bsdfsdf);
print join('   ',sort @chief);
[root@localhost scripts]# ./shuzu1.pl
Adfhdf   Bsdfsdf   Csdfsd   Fsdfsdf   Zdfghdh


你可以使用飞船运算符< = >。飞船运算符因为从侧面看它像一个飞行的碟子而得名。
如果它左边的操作数小于右边的操作数,那么它返回- 1,如果左边的操作数大于右边的操作
数,则返回0:

阅读(3748) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~