List & Array
While Scalar is single value, list is a list of scalars in order. Every element of a list is a dependant scalar, it can be number or characters.
Array is the variable of list, list is the values of array. In Perl array and list are almost the same meaning: a list of scarlars.
Every element of array is kept with its index, starting from [0].
$fred[0]="yabba";
$fred[1]="dabba";
$fred[2]="doo";
Arrays and Scalars have different namespaces, such as $fred[0] and $fred can be used at the same time, Perl won't be confused, but maybe the maintainer will, so don't play Perl like that.
We can do whatever to array elements like we do to a scalar.
print $fred[0];
$fred[2]="didley";
print $fred[$number-1];
Like the last example, we can use variable and expression in array's index. Element without a value will be undef.
Array can grow its length automatically if you give values to a certain index.
$rocks[0]='bedrock';
$rocks[1]='slate';
$rocks[2]='lava';
$rocks[3]='crushed rock';
$rocks[99]='schist'; # 95 undef elements created!
There are two ways to directly get the last element of an array:
$rocks[$#rocks]='hard rock';
$rocks[-1]='hard rock';
$#rocks is the index of last element, both above ways are correct, but [-1] is more popular ^_^
list/array can be writen in ( ), split by ',' between neighbour elements.
(1, 2, 3)
(1, 2, 3,) # same as above
() # empty list, containing 0 element
(1 .. 100) # a list of 100 int
(5 .. 1) # empty list, .. is order sensitive
(2, 2 .. 6, 10, 12 ) # same as (0, 2, 3, 4, 5, 6, 10, 12)
("fred", "barney", "betty", "milma", "dino") # list of characters
($m .. $n)
(0 .. $#rocks)
($m, 17) # two values
($m+$0, $p+$q) # two values
The last 4 examples shows element can be variable and/or expression too.
List of characters are very common, qw was designed for this. qw means 'quotes Words', it works as a piar of ' .
qw(fred barney betty wilma dino) # same as ('fred', 'barney', 'betty', 'milma', 'dino')
qw will ignore the whitespace (spaces, tabs newlines), and the ( ) can be other symbols.
qw ! fred barney betty wilma dino !
qw# fred barney betty wilma dino # # like comments
qw( fred barney betty wilma dino )
qw{ fred barney betty wilma dino }
qw[ fred barney betty wilma dino ]
qw< fred barney betty wilma dino >
qw{
/usr/dict/words
/home/rootbeer/.ispell_english # a Good way representing Unix paths
}
Like scalar, we can give values to list.
($fred, $barney, $dino)=("flintstone", "rubble", undef);
($fred,$barney)=($barney,$fred); # a simple way to replace values of varables
($betty[0],$betty[1])=($betty[1],$betty[0]);
($fred,$barney) = qw<flintstone rubble slate granite>; # slate and granite will be ignored
($wilma,$dino) = qw[flintstone]; # $dino is undef
We can use @ to give values to an array.
@rocks=qw/bedrock slate lava/;
@tiny=(); # empty list
@stuff=(@giant, undef, @giant);
0