加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl Learning - 4 (pop/push/shift/unshift, foreach, $_)

发布时间:2020-12-15 21:03:00 所属栏目:大数据 来源:网络整理
导读:pop() push() ? pop() get the last element out of array,and returns that element. ? @array=5..9; $fred=pop(@array);?# $fred is 9,@array now is (5,6,7,8) $barney=pop @array;?# $barney is 8,7) pop @array;??# @array now is (5,6) ? Retuned valu
pop() & push()
?
pop() get the last element out of array,and returns that element.
?
@array=5..9;
$fred=pop(@array);?# $fred is 9,@array now is (5,6,7,8)
$barney=pop @array;?# $barney is 8,7)
pop @array;??# @array now is (5,6)
?
Retuned value can be throw away,it's ligal in Perl.
If array is empty,pop() do nothing and returns undef.
The ( ) after pop can be skipped,Perl says if skipping something doesn't make difference,then let's skip it.
?
push() do the oppsite things to pop(),it adds elements to the end of an array.
?
push(@array,0);??# @array now is (5,0)
push @array,8;??# @array now is (5,8)
push @array,1..10;?# 10 more elements
@others=qw/9 0 2 1 0/;
push @array,@others;?# 5 more elements
?
Note the fist parameter of push() and the only parameter of pop() must be an array.
?
shift() & unshift()
?
Shift() removes the first element out of an array,unshift() adds elements to the beginning of an array.
?
@array=qw#dino fred barney#;
$m=shift(@array);??# $m is 'dino',@array now is ('fred','barney')
$n=shift @array;??# $n is 'fred',@array now is ('barney')
shift @array;???# @array now is empty ()
$o=shift @array;??# @array still empty,$o is undef
unshift(@array,5);??# @array becomes (5)
unshift @array,4;??# @array becomes (4,5)
@others=1..3;
unshift @array,@others;??# @array becomes (1,2,3,4,5)
?
Array cen be inserted to pire of " ",element will be serarated by space automatically.
?
@rocks=qw{flintstone slate rubble};
print "quartz @rocks limestonen";?# prints "quartz flintstone slate rubble limestone"
?
It will not present spaces before the head or after the end of array,just add space between elements.
?
foreach() can go through all elements of an array and produce a loop.
?
foreach $rock (qw/bedrock slate lava/){
??? print "One rock is $rock.n";
??? }
?
The contral variable $rock get an element every time it loops,until the last element it ends.
The contral variable changes the values of elements when it loops,not only getting a copy.
?
If there is another variable with same name as the contral variable,when loop starts the varable cannot change.
Until loop ends,the variable recovers it's original value ahead of loop.
?
If no contral variable is determined,Perl uses $_ as contral variable.
?
foreach(1..10){
??? print "I can count to $_!n";
??? }
$_="Yabba dabba doon";
print;???# $_ will be printed
Whenever you cannot find a varable,it could be a $_ working there ^_^

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读