Using the Perl push() function

文章推薦指數: 80 %
投票人數:10人

You can use the push function to add new elements to the end of an array. Example 1. Adding an item onto an array. You can use push to push an element onto the ... StartHere FAQs HOWTOs TUTORIALs MostRecent Miscellaneous Sitemap ProvideFeedback Home » Howtos » Perlfunc » Pushfunction Tweet UsingthePerlpush()function Introduction Youcanusethepushfunctiontoaddnewelementstotheendofanarray. Example1.Addinganitemontoanarray Youcanusepushtopushanelementontotheendofanarray: #!/usr/bin/perl usestrict; usewarnings; my@planets=qw(mercuryvenusearthmars); print"@planets\n"; push(@planets,'jupiter'); print"@planets\n"; exit0; Thisprogramproducesthefollowingoutput: mercuryvenusearthmars mercuryvenusearthmarsjupiter Youcanseethat'jupiter'isnowontheendofour@planetsarray. Thepushfunctionreturnsthenumberofelementsinthearrayafterthenewvalue(s)havebeenappended.Ifwewantedtoseehowmanyplanetswereinthemodified@planetsarray,wecouldchangeourcodeasfollows: #!/usr/bin/perl usestrict; usewarnings; my@planets=qw(mercuryvenusearthmars); print"@planets\n"; my$number_of_planets=push(@planets,'jupiter'); print"@planets\n"; print"Thenumberofplanetsis:$number_of_planets\n"; exit0; Theoutputisnow: mercuryvenusearthmars mercuryvenusearthmarsjupiter Thenumberofplanetsis:5 Example2.Joiningtwoarraystogether Youcanalsousepushtoappendanarrayontotheendofanotherarray: #!/usr/bin/perl usestrict; usewarnings; my@planets=qw(mercuryvenusearthmars); my@outer_planets=qw(jupitersaturnuranusneptunepluto); print"@planets\n"; push(@planets,@outer_planets); print"@planets\n"; exit0; Asthefollowingoutputdemonstrates,the@outer_planetsarrayhasbeenaddedtotheendofthe@planetsarray: mercuryvenusearthmars mercuryvenusearthmarsjupitersaturnuranusneptunepluto Example3.Addingtoanarrayreference Youcanusepushtoappendelementsontotheendofareferencetoanarray,butyoumustdereferenceitfirst: #!/usr/bin/perl usestrict; usewarnings; my@planets=qw(mercuryvenusearthmars); my$planets_ref=\@planets; push(@{$planets_ref},qw(jupitersaturnuranusneptunepluto)); #Couldalsobewrittenas: #push(@$planets_ref,qw(jupitersaturnuranusneptunepluto)); print"@{$planets_ref}\n"; #Couldalsobewrittenas: #print"@$planets_ref\n"; exit0; Thisproducesthefollowingoutput: mercuryvenusearthmarsjupitersaturnuranusneptunepluto Seealso perldoc-fpush perldoc-fpop perldoc-fshift perldoc-funshift perldoc-q"differencebetweenalistandanarray" Revision: 1.3 [Top]



請為這篇文章評分?