Perl Array Functions
pop()
#!/usr/local/bin/perl
@list = qw(one, two, three) # initialize @list
$last = pop(@list); # $last is the last elemenet in the list
print ("$last\n"); # prints $last and goes to a new line
_END_
Result: three
push()
#!/usr/local/bin/perl
@list = (1, 2, 3); # initialize @list
push (@list, 10, 20, 30); # @list now equals (1, 2, 3, 10, 20, 30)
print ("@list\n"); # prints @list and goes to a new line
_END_
Result: 1 2 3 10 20 30
unshift()
#!/usr/local/bin/perl
@list = qw(one, two, three); # initialize @list
$new_number = ("four"); # set $new_number to "four"
unshift (@list, $new_number); # @list is now (four, one, two, three)
print ("@list\n"); # prints @list and goes to a new line
_END_
Result: four, one, two, three
shift()
#!/usr/local/bin/perl
@list = qw(one, two, three); # initialize @list
$first = shift(@list); # $first is set to the 1st element
print ("$first\n"); # prints $first and goes to a new line
_END_
Result: one
sort()
#!/usr/local/bin/perl
@list = qw(March April May); # initialize @list
@list = sort(@list); # @list is now ("April","March","May")
print ("@list\n"); # prints @list and goes to a new line
_END_
Result: April March May
splice()
#!/usr/local/bin/perl
@list = qw(three four five); # initialize @list
@list2 = qw(two one); # initialize @list2
splice (@list2, 1, 1, @list); # this replaces the last element of @list2
("one") with the first element of @list2
print ("@list2\n"); # prints new @list2 and goes to a new line
_END_
Result: two three four five
split()
#!/usr/local/bin/perl
@list = qw(Hello Professor Horn); # initialize @list
split (/ /,@list); # separates each element of the string into an
array at each occurrence of a space
print ("@list\n"); # print entire string
print ("@list[0]\n"); # prints first element of string
print ("@list[1]\n"); # prints second element of string
print ("@list[2]\n"); # prints third element of string
_END_
Result: Hello Professor Horn
Hello
Professor
Horn
neat tricks
#!/usr/local/bin/perl
@list = qw(Programming with Perl); # initialize @list
@reverse_list = reverse(@list); # reverses order of elements in string
print ("@reverse_list\n"); # prints reverse of string and goes to a new
line
@slice = (@list[1..2]); # sets @slice equal to the second through
third elements in the string
print ("@slice\n"); # prints @slice ("with Perl") and goes to a
new line
_END_
Result: Perl with Programming
with Perl