The arrays you've always dreamed of
Perl also offers arrays as another type of variable.
Arrays are denoted by the "@" symbol. Arrays in Perl are dynamic, that is, you don't specify their size. They grow and shrink as you like, and perform operations you can only dream of in other languages. Array manipulation is one of the things that make Perl so awesome. You'll see why next.
Code: Select all
#!/usr/bin/perl
use strict;
# Declaring an array
my @array_example;
# Assigning elements
$array_example[0] = "Hello ";
$array_example[1] = "world\n";
# Printing the array
print(@array_example);
# Printing how many elements the array has
# $# returns last array index in use
print($#array_example + 1);
# Another array initialization
@array_example = ("Bye bye", " ", "world!\n");
print("\n");
print(@array_example);
print($#array_example + 1);
# Yet another array initialization
@array_example = qw(this 'never' ends "\n");
print("\n");
print(@array_example);
print($#array_example + 1);
# Emptying the array
@array_example = ();
print("\n");
print(@array_example);
print($#array_example + 1);Arrays in Perl allow some wonderfully easy manipulations, like:
Code: Select all
#!/usr/bin/perl
use strict;
my @array_example = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
# Get sub array from index 3 to 6
my @sub_array = @array_example[3..6];
print('@array_example[3..6]: ');
print("@sub_array\n");
# Get sub array with index one and from index 5 to 9
@sub_array = @array_example[1, 5..9];
print('@array_example[1, 5..9]: ');
print("@sub_array\n");
# Joins array elements using the specified character
my $joined = join(", ", @array_example);
print('join(): ');
print("$joined\n");
# Splits string into array using ", " as delimiter
my @aux = split(/, /, $joined);
print('split(): ');
print("@aux\n");
# Adds element at end
push(@array_example, 10);
print('push(): ');
print("@array_example\n");
# Removes and returns first element
my $first_element = shift(@array_example);
print('shift(): ');
print("@array_example\n");
# Array made of variables
my $elem0 = 0;
my $elem1 = 1;
my $elem2 = 2;
my $elem3 = 3;
my @new_array = ($elem1, $elem0, $elem3, $elem2);
print('my @new_array = ($elem1, $elem0, $elem3, $elem2): ');
print("@new_array\n");
# Variable split an array
my ($one, $two, $three, @rest) = @array_example;
print('my ($one, $two, $three) = @array_example: ');
print("$one, $two, $three\n");
print('@rest: ');
print("@rest\n");unshift() -> adds an element to the beginning of an array
pop() -> removes the last element of an array
delete() -> removes an element by index number
sort() -> sorts array
<< Previous | Next >>
Advertising

