linux poison RSS
linux poison Email

Perl Script: Array examples and Operations

Below perl script demonstrate the usage of array and show all sort of operation that can be done on the array.

Feel free to copy and use this script:

Source: cat array.pl
#!/usr/bin/perl

@array = ("a", "b", "c", "d");

# Get the lengthe of array
$LEN = @array;
print "Length of the array is:  $LEN \n";

# Print the array elements"
print "@array \n";
print "-------------------------\n";

# Iterate through the array
for ($i=0; $i<=$#array; $i++) {
        print "$array[$i]\n";
}
print "-------------------------\n";

# Add a new element to the end of the array
push(@array, "e");
print "@array \n";
print "-------------------------\n";

# Add an element to the beginning of an array
unshift(@array, "z");
print "@array \n";
print "-------------------------\n";

# Remove the last element of an array.
pop(@array);
print "@array \n";
print "-------------------------\n";

# Remove the first element of an array.
shift(@array);
print "Back to original array .... \n";
print "@array \n";
print "-------------------------\n";

# Copying from One Array Variable to Another
@copy_array = (@array);
print "Element in the new array are: @copy_array \n";
print "-------------------------\n";

# Sort the array element
@list = ("x" , "q", "p" , @array, 1, 3, 5, 9);
@sort_list = sort(@list);
print "Here is the sorted array: @sort_list \n";
print "-------------------------\n";

Output: perl array.pl
Length of the array is:  4
a b c d
-------------------------
a
b
c
d
-------------------------
a b c d e
-------------------------
z a b c d e
-------------------------
z a b c d
-------------------------
Back to original array ....
a b c d
-------------------------
Element in the new array are: a b c d
-------------------------
Here is the sorted array: 1 3 5 9 a b c d p q x
-------------------------




0 comments:

Post a Comment

Related Posts with Thumbnails