140 likes | 271 Views
Perl. Hour 4 Lists and Arrays. Lists. List is a sequence of scalars Surrounded by parentheses; items separated by commas (‘a’, 5, $alfa, ‘$_’, “the $item”) Usual variable substitution rules apply. List Shortcuts. qw(the $speed $color fox) Creates list from each word with single quotes
E N D
Perl Hour 4Lists and Arrays
Lists • List is a sequence of scalars • Surrounded by parentheses; items separated by commas • (‘a’, 5, $alfa, ‘$_’, “the $item”) • Usual variable substitution rules apply
List Shortcuts • qw(the $speed $color fox) • Creates list from each word with single quotes • qqw(the $speed $color fox) • Creates list from each word with double quotes • (1 .. 9, 11..15) • Range of numbers
Arrays • Lists occur in code but arrays variables are needed to store and manipulate list values • @names = qw(Joe, Jill, Mary, Bill); • @empty = (); • @double = (@names, @names); • Array is flattened to list
Arrays (cont.) • @nums = (1..10); • ($first, @rest, $last) = @nums • $first = 1; $last = 10; @rest = (2..9); • ($f,$n) = @nums • $f=1; $n=2; ignore rest • ($a, $b, $c) = qqw(a b) • $a=“a”; $b=“b”; $c = undef;
Array Subscripts • Zero-based subscripts • @nums = (1..10); • $nums[0] • gives or takes the first element • @nums[1,2,5,7,9] is array slice • $nums[-1] • Last element; -2 is next to last, etc.
Array Size • $#array • Returns highest subscript of array • Setting it changes size of array • $size = @array • Gives size of array
Context • Determines effect of operations • Scalar context • Operations use scalars • List context • Operations use lists (or arrays) • In assignment, left side determines context
Context (cont.) • $a=$b; #scalar context • @m=@n; #list context • $b=@list; #scalar context • @a=$b; #list context, one element list • $line=<STDIN>; #scalar so one line • @input=<STDIN>; #list so whole file • ($x)=<STDIN>; #list, but what?
Context (cont.) • Context can have significant effects • @start=(“*”) x 100; #array size 100 of “*” • $which=(‘a’, ‘b’, ‘c’); #scalar comma expr • localtime function • Scalar: formatted date string • List: array of date/time components
Stepping through an array • foreach $i (1..10) { … } • foreach (@name) { … } • Uses $_ • Modifying the control variable alters the corresponding entry in the array
Split and join • split(/ /, $words); • Splits string words on blanks • First argument is a pattern, a regular expression to match between items • //, the empty string splits each letter • join(‘, ‘, (1..5)) • Inserts comma space between numbers
Sorting • @alist = sort @names; • Alphabetic sort • @snum = sort {$a <=> $b; } (5, 3, 7, -1); • Can specify any code block or function to determine sort order. Must return -1, 0, or 1 to indicate order