Nano's Blog

01/05/2010

The pop and push Operators

Filed under: programming — Tags: — nano @ 13:55

The pop operator takes the last element off of an array and returns it;

The converse operation is push, which adds and element (or a list of elements) to the end of array.

The first argument to push or the only argument for pop must be an array variable – pushing and poping would not make sense on a literal list.

#!C:\Perl\bin\perl.exe
use strict; # enabled
use warnings; 

my @array; 

@array  = 5..9;
my $fred   = pop(@array);  # $fred gets 9, @array now has (5, 6, 7, 8 )
my $barney = pop @array;   # $barney gets 8, @array now has (5, 6, 7)
pop @array;             # @array now has (5, 6). (The 7 is discarded.)

print $fred;
print "\n";
print $barney;
print "\n";
print @array;
print "\n";

my @others;
push(@array, 0);      # @array now has (5, 6, 0)
push @array, 8;       # @array now has (5, 6, 0, 8 )
push @array, 1..10;   # @array now has those ten new elements
@others = qw/ 9 0 2 1 0 /;
push @array, @others; # @array now has those five new elements (19 total)

print @others;
print "\n";
print @array;

Output

9
8
56
90210
56081234567891090210

- from Learning Perl 5E

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress