Nano's Blog

01/16/2010

The shift and unshift Operators

Filed under: programming — Tags: — nano @ 02:39

The shift and unshift operators perform the corresponding actions on the “start” of the array (or the “left” side of an array, or the portion with the lowest subscripts).
push and pop operators do things to the “end” of an array(or the “right” sidce of an array).

The foreach control involved to the sample code below.

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

my @array = qw# dino fred barney #;
# print @array;
foreach my $array (@array) {
$array = "\t$array"; # put a tab in front of each element of @rocks
$array.= "\n"; # put a newline on the end of each
print $array;
}

my $m = shift(@array); # $m gets "dino", @array now has ("fred", "barney")
my $n = shift @array; # $n gets "fred", @array now has ("barney")
shift @array; # @array is now empty
# print a empty array
foreach my $array (@array) {
$array = "\t$array"; # put a tab in front of each element of @rocks
$array.= "\n"; # put a newline on the end of each
print $array; # nothing printed
}

my $o = shift @array; # $o gets undef, @array is still empty
unshift(@array, 5); # @array now has the one-element list (5)
unshift @array, 4; # @array now has (4, 5)
my @others = 1..3;
unshift @array, @others; # @array now has (1, 2, 3, 4, 5)
foreach my $array (@array) {
$array = "\t$array"; # put a tab in front of each element of @rocks
$array.= "\n"; # put a newline on the end of each
print $array;
}

Output:


D:\learning\perl>hi.pl
        dino
        fred
        barney
        1
        2
        3
        4
        5

D:\learning\perl>

- from Learning Perl 5E

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress