Thursday, October 2, 2008

perl: arrays and hashes

This is mostly a reminder for me than an article for everybody as I haven't touched perl for ages.

Small reference on arrays and hashes in perl.

Arrays

Declaration

@array = (1, '1', (2));
@array = (1..20);# by range
Access to array members with index
$array[0];
Define reference to array
$array = \@array; #reference to another array
$array = [1, 3, 5, 7, 9]; #reference to anonymous array
$array = [ @array ]; #reference to anonymous copy
@$array = (2, 4, 6, 8, 10); #implicit reference to anonymous array
To deference reference to array put @ or $ before $
@array = @$array;
@array = $$array;
Access to members of array by reference with index
$array->[0];# using -> operator
@$array[0];# dereferencing
$$array[0];# dereferencing
Size of the array
$#array;# [note: size of an empty array is -1, so $#array is a number of elements - 1]
Here is a tricks to remove all elements from an array, add an element to array
$#array = -1;
$c[++$#c] = 'value';
Take a slice of an array
@array[0..2];# first, second and third elements
@array[0,2];# first and third elements
Hashes

Declaration
%hash = ('key0', 'value0', 'key1', 'value1');# amount of elements must be even
%hash = ('key0' => 'value0', 'key1' => 'value1');
Access to hash members with key
$hash{'key0'};
Define reference to hash
$hash = \%hash; #reference to another hash
$hash = {1 => 3, 5 => 7}; #reference to anonymous hash
$hash = {1, 3, 5, 7}; #reference to anonymous hash; amount of elements must be even
$hash = [ %hash ]; #reference to anonymous copy
%$hash = (2, 4, 6, 8); #implicit reference to anonymous hash; amount of elements must be even
%$hash = (2 => 4, 6 => 8); #implicit reference to anonymous hash
To deference reference to hash put % or $ before $
%hash = %$hash;
%hash = $$hash;
Access to members of hash by reference with key
$hash->{'key0'};# using -> operator
%$hash[0];# dereferencing
$$hash[0];# dereferencing
Size of the hash
scalar keys(%hash)
Take a slice of a hash
@hash{'key0','key1'};
@hash{@keys};

No comments: