70 likes | 143 Views
Perl Chapter 4. Arrays. foreach loop. Iterative statement to process array elements control based on number of elements in array or list literal foreach [scalar_var] (list_literal or array_name) { … } [scalar_var] optional - $_ used [scalar_var] local to the loop. examples.
E N D
Perl Chapter 4 Arrays
foreach loop • Iterative statement to process array elements • control based on number of elements in array or list literal foreach [scalar_var] (list_literal or array_name) { … } • [scalar_var] optional - $_ used • [scalar_var] local to the loop
examples foreach $age (@ages) { $age++; } #age is now undef $sum=0; foreach $index (0..99){ $sum += $list[$index]; }
list operators • reverse - @rnames = reverse @names; • sort - @sorted_names = sort @names; • list of numbers sorted as STRINGS • Chapter 6 talks more about sorting
split function • opposite of join • takes strings apart – assigned to array often • split /pattern/, expression, limit • where /pattern/ is a regular expression
split /pattern/, expression, limit /:/ “lsk:jfkd:skld:” absent is whitespace $stringVar // $_ splits into individual characters @chars=split //, “kumquats”; “k”, “u”, “m”, “q”, “u”, “a”, “t”, “s”
$line=<STDIN>; type in Bobby Sue Jones ($fname, $mname, $lname)= split / /, $line; or ($fname, $mname, $lname) = split $line; • limit specifies max number of substrings to produce @fruit=split /,/, apples,grapes,pineapples,bananas”, 3; results in @fruit (“apples”, “grapes”, “pineapples,bananas”) • /pattern/ can get quite complex Chapter 7