Reflections on perl push usage and subroutine return values

Source: Internet
Author: User

The pop operation extracts the last element of the array and returns the result:

@ Array = 5 .. 9;
$ Fred = pop (@ array); # $ fred gets 9, @ array is (,) now)
$ Barney = pop @ array; # $ barneygets8, @ array is (5, 6, 7)
Pop @ array; # @ array: (5, 6) (7 discarded)
In the last example, pop is used in "inavoidcontext", that is, it does not store the returned value. It is legal to use pop in this way.

If the array is empty, pop does not do anything (because no element can be removed), and undef is returned.

You may have noticed that you can use or do not use parentheses after pop. This is a general rule in Perl: If the meaning of the parentheses is not changed, brackets are optional.
. The opposite operation to pop is push, which can add an element (or a column of elements) to the end of the array:
◆ People with corresponding education will find that this is a synonym repetition.
Push (@ array, 0); # @ array: (5, 6, 0)
Push @ array, 8; # @ array)
Push @ array, 1 .. 10; # @ array now has 10 more elements
@ Others = qw/9 0 2 1 0 /;
Push @ array, @ others; # @ array now has 5 more elements (19 in total)
The first parameter of push or the unique parameter of pop must be an array variable.

Copy codeThe Code is as follows :#! /Bin/perl
Sub above_average
{
$ Number = @_;
Foreach $ how (@_)
{
$ Total = $ total + $ how;
}
$ The_average = $ total/$ number;
Foreach (@_)
{
If ($ _> $ the_average)
{
Push (@ larger, $ _) # You don't need to assign values here. You just need to use push to add array elements.
}
}
@ Larger; # the return value of the subroutine must be included. It was not written at the beginning.
}
Print "please input several numbers, and you will get the number which is large than their average \ n ";
@ The_number_input = <STDIN>;
@ The_number_larger = above_average (@ the_number_input );
Print "@ the_number_larger \ n ";
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.