Perl Arrays

Fundamental operations

# Declare array
my @elements = ('one', 'two', 'tree', 'four');

# Access elements
say $elements[0];
say $elements[1];
say $elements[2];
say $elements[3];

# Get array size
say 'Number of elements: ' . @elements;

See http://modernperlbooks.com/books/modern_perl_2014/03-perl-language.html#QXJyYXlBc3NpZ25tZW50

Element manipulation

  • pop: remove and return the last element
  • shift: remove and return the first element
  • push: add element(s) at the tail
  • unshift: add element(s) at the top

See http://perlmaven.com/manipulating-perl-arrays

Sort elements

Sort acending:

my @ascending_sorted_list = sort {$a <=> $b} @original_list;

Sort descending:

my @descending_sorted_list = sort {$b <=> $a} @original_list;

Using a custom sort function:

sub cmp_value
{
    return $a <=> $b;
}

my @sorted_elements = sort cmp_value @elements;

See http://perldoc.perl.org/functions/sort.html

Miscellaneous

  • grep
  • join: Create a string out of an array
  • map
  • qw//
  • reverse
  • unpack

Read more