perl-basic-数组操作
RT。。。直接看代码
my @stack = ("Fred", "Eileen", "Denise", "Charlie"); # remove at tail pop @stack; print @stack; # add to tail push @stack, "Bob", "Alice"; print @stack; # remove at head shift @stack; print @stack; # add to head unshift @stack, "Hank", "Grace"; print @stack; # 其实pop,push,shift,unshift是特殊的splice my @stack = ("Fred", "Eileen", "Denise", "Charlie"); # splice 返回分割结果,这里是得到EileenDenise print splice(@stack, 1, 2, "<<<", ">>>"); print "\n"; # 将分割结果替换为<<<和>>> print @stack; print "\n";
- 实用函数
- join and reverse
my @elements = ("Antimony", "Arsenic", "Aluminum", "Selenium"); print @elements; # "AntimonyArsenicAluminumSelenium" # 有了空格:) print "@elements"; # "Antimony Arsenic Aluminum Selenium" # 使用,连接 print join(", ", @elements); # "Antimony, Arsenic, Aluminum, Selenium" # list,所以按元素逆序 print reverse("Hello", "World"); # "WorldHello" # 前面加了scalar,所以即使是list,也先组合在一起,然后按字母逆序 print scalar reverse("Hello", "World"); # "dlroWolleH"
- map and grep
my @capitals = ("Baton Rouge", "Indianapolis", "Columbus", "Montgomery", "Helena", "Denver", "Boise"); # 对@capitals中的元素使用uc函数 # http://perldoc.perl.org/functions/map.html print join ", ", map { uc $_ } @capitals; # "BATON ROUGE, INDIANAPOLIS, COLUMBUS, MONTGOMERY, HELENA, DENVER, BOISE"