Home >> perldatatypes >>Perl Arrays@array = (11, 22, "perlhome","perl array"); ## a 4 element array @empty_arr = (); ## the array with 0 elements @array_learn = (1, 2, "hello", "world"); $array_learn[0] = $array_learn[0] + $array_learn[1];## $array_learn[0] is now 3If code attempts to read an element outside the array size, undef is returned. If code writes outside the array size, the array grows automatically to be big enough. like in above case $array_learn[10] will return undef. @array = (1, 2, "hello", "there"); $sum = $array[0] + $array[27]; ## $sum is now 1, since $array[27] returned undef $array[99] = "the end"; ## array grows to be size 100When used in a scalar context, an array evaluates to its length. The "scalar" operator will force the evaluation of something in a scalar context, so you can use scalar() to get the length of an array. As an alternative to using scalar, the expression $#array is the index of the last element of the array which is always one less than the length. @array = (1, 2, "hello", "there"); $len = @array; ## $len is now 4 (the length of @array) $len = scalar(@array); ## same as above, since $len represented a scalar ## context anyway, but this is more explicit @letters = ("a", "b", "c");
$i = $#letters;## $i is now 2
That scalar(@array) is the way to refer to the length of an array is not a great moment in the history of readable code. At least I haven't showed you the even more vulgar forms such as (0 + @a). The sort operator (sort @a) returns a copy of the array sorted in ascending alphabetic order. Note that sort does not change the original array. Here are some common ways to sort... (sort @array)
## sort alphabetically, with uppercase first
(sort {$a <=> $b} @array)
## sort numerically
(sort {$b cmp $a} @array)
## sort reverse alphabetically
(sort {lc($a) cmp lc($b)} @array)
## sort alphabetically, ignoring case (somewhat inefficient)
Perl functions
|
Perl @ARGV %ENV Perl Data Types Perl Hash Perl list Perl references Perl Scalar data types Perl Special Variables
|