perl 第九弹 函数II
Posted 流浪骆驼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了perl 第九弹 函数II相关的知识,希望对你有一定的参考价值。
上期回顾
函数
join函数能够把数组元素连接到单个字符串中,并借助指定的定界符划分各个数组元素。
用法:join(DELIMITER, LIST)
$name="Joe Blow";
$birth="11/12/86";
$address="10 Main St.";
# 通过:将三个变量连接起来
print join(":", $name, $birth, $address ), " ";
@all = (1..10);
# 通过-将数组@all的全部元素连接起来
print join("-", @all), " ";
__END__
(output)
Joe Blow:11/12/86:10 Main St.
1-2-3-4-5-6-7-8-9-10
$line="a b c d e";
# 按照空格拆分,@letter = ("a","b","c","d","e")
@letter=split(' ',$line);
# 指定拆分为3份,@letter = ("a","b","c d e")
@letter=split(' ',$line , 3);
# 通过DATA句柄读取脚本内12-15行数据
while(<DATA>){
# 每行按照:拆分
@line=split(":");
# 输出$line[0]
print "$line[0] ";
}
__DATA__
Betty Boop:245-836-8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500
Igor Chevsky:385-375-8395:3567 Populus Place, Caldwell, NJ 23875:6/18/68:23400
Norma Corder:397-857-2735:74 Pine Street, Dearborn, MI 23874:3/28/45:245700
Jennifer Cowan:548-834-2348:583 Laurel Ave., Kingsville, TX 83745:10/1/35:58900
Fred Fardbarkle:674-843-1385:20 Park Lane, Duluth, MN 23850:4/12/23:78900
__DATA__ 特殊实量表示一个文件句柄,允许用户处理来自脚本的文本数据,而非外来数据。
@n = (2, 4, 6, 8);
# 数组@n中的 每个元素 * 2 + 6 , 转化后的数组重新赋值给@n
@n = map $_ * 2 + 6, @n;
print "@nn";
__END__
(output)
10 14 18 22
用法:splice(ARRAY, OFFSET, LENGTH, LIST)
splice(ARRAY, OFFSET, LENGTH)
splice(ARRAY, OFFSET)
@colors=("red", "green", "purple", "blue", "brown");
# splice 函数将移除从index 为2开始的两个元素:purple 和blue,
# 并将删除的元素返回到另一个名为@discarded 的数组
@discarded = splice(@colors, 2, 2);
print "The elements removed after the splice are: @discarded.n";
print "The spliced array is now @colors.n";
__END__
(output)
The elements removed after the splice are: purple blue.
The spliced array is now red green brown.
sort 函数能返回经过排序后的数组。(本次为简单用法)
用法:sort(LIST)
@list=("dog","cat", "bird","snake" );
# 对@list进行排序
@sorted = sort(@list);
print "Ascii sort: @sortedn";
__END__
(output)
Ascii sort: bird cat dog snake
sort函数默认执行字符串(ASCII)排序。排序得到的值必须赋值到另一个数组或原数组中。sort 函数不会改变原数组的内容。
总结
以上是关于perl 第九弹 函数II的主要内容,如果未能解决你的问题,请参考以下文章