next up previous
Next: About this document Up: No Title Previous: No Title

Lists

1. Basics

A list (or array) means a list of scalar values, each a number or string. It could have any name, but let's use @v to keep it short.

@v name of a list, or more accurately, a variable name with a list marker

$v[0] first value in @v ; note the dollar sign

$#v index of the last value in the list, -1 if list is empty

$v[$#v] last value in the list

2. Some ways of making a list:

@v = (2,3,5); or @v = ("cat","dog","cow");

@v = 0..5; (``range operator'') same as @v = (0,1,2,3,4,5)

@v = <>; the whole input text, as a list of lines (each with )

@v = <STDIN>; the whole standard input text, as a list of lines

@v = split(" ",$s); or @v = split " ",$s; split a string at white space

push(@v,"hi"); append (add) string to the end of a list (see pop below)

@v = `ls`; run a UNIX command and save the output as a list of lines.

3. Some ways of using a list:

$v[3] take a member of the list

($a,$b,$c) = @v; put list values into some scalars, all at once.

"the list is @v" list turned into part of a string (best if @v doesn't have any newlines in it), or

print "v = @v"; the way you might do it for diagnostic output

print @v; print the whole list (which presumably has newlines in it)

$n = scalar @v; the length of a list, same as $n = 1 + $#v;

join("|",@v); make the list into a string with list values separated by a vertical bar

foreach $i (@v)... loop on values in a list

foreach (@v)... loop on values in a list, putting them into $_ , the default string.

4. Lists to lists

@v = sort @w; sort a list

@v = reverse @w; reverse a list

@v = reverse sort @w; reverse sort a list

5. Operations that change a list ``in place''

push(@v,"hi"); append to list, as above

pop(@v); or $s = pop(@v) take the last value off a list

splice(@v,2,3,@w); in list @v , starting at index 2, remove three values and replace them by @w .

shift @v; shift list left one, losing first value

chomp @v strip trailing newlines, if any, from all list values

6. Other things

@ARGV the list of arguments with which the script is called

@_ default list (often used to hold subroutine arguments)

keys

Note. In the examples above where it says @v = , the right-hand side can be used anywhere that a list is appropriate.


next up previous
Next: About this document Up: No Title Previous: No Title

Kirby A. Baker
Thu Jan 21 18:58:58 PST 1999