Perl Lists and Arrays by bzs12927

VIEWS: 0 PAGES: 16

									Perl Lists and Arrays
   CSC 492 Topics in Perl
         Joe Reynoldson
        January 19, 2005
 Getting Plural in Perl
 List literals
     An unnamed collection of scalars separated by commas and
      enclosed by parenthesis
     Lists can contain any combination of scalar values
                  (5, 7, 9, 11)
                  („string‟, 0, undef, $var1)
                  ()
                  (undef)

 Arrays
     Named variables which store lists
     The type identifier for arrays is @
     The array namespace is separate from the scalar namespace, so
      $list and @list are 2 different variables
Accessing array elements
 Arrays are indexed by integers starting at zero
 The type identifier of an single array element is $
 All array subscripts are converted to integers
 Subscripts can also be expressions
 The subscript of the last element in an array is
  stored in the special variable $#array_name
  @name_list = (); #create an empty array
  $first = 0;
  $name_list[0] = 'joe'; #assign the first element
  $name_list[1.5] = 'molly'; #assign the second element
  print $name_list[$first],"\n"; #prints joe
  print $name_list[$first + 1],"\n"; #prints molly
  print $name_list[$#name_list],"\n"; #also prints molly
Array sizes

Perl will automatically make an array
 larger as necessary
There are several methods to change the
 size of an array

  @small_list = (1, 2, 3); #3 items
  @big_list = (@small_list, @small_list); #6 items
  $#big_list = 499; #add 494 items
  @small_list = (); #the empty list
  @big_list = undef; #1 item
List Shortcuts
 The range operator ( x..y ) creates a list starting from its left-hand
  operand and going *up* to its right-hand operand
 $first_num = 1; $last_num = 100;
 @numbers = ($first_num..$last_num); # $#numbers == 99


 Create a list of strings without all of the quotes using the qw operator

 @sammy = qw/ turkey mayo cheese lettuce tomato /;
 @paths = qw( /usr/bin /usr/local/bin /usr/X/bin );


 Assign to a list of scalar variables in one statement

 ($fruit,$vegetable,$meat)=qw( pineapple asparagus beef );
 ($array[0], $array[1]) = ($array[1], $array[0]); #swap!
Array operators
 push adds onto the end of an array
    $count = 0;
    while($count < 10){ push(@numbers, ++$count); }

 pop removes elements from the end of an array
while($last_number = pop(@numbers)){ print $last_number; }


 unshift adds elements to the beginning of an array
       unshift(@numbers, (1 .. 10));

 shift removes elements from the beginning of an array
     while(@numbers){ print shift(@numbers); }

        ** Check out Llama book pp 46-47 for more examples
Array interpolation
 arrays within double quotes will be interpolated
            @array = (1 .. 10);
            print "@array\n";

            1 2 3 4 5 6 7 8 9 10

 printing email addresses becomes tricky (llama
  page 48)
 printing just the array results in no spaces
            print @array,"\n";

            12345678910
My favorite loop is foreach
 use foreach to iterate over a list of elements
         foreach $line (@file){ print "$line";}

         $scope = '206.176.3';
         foreach $number (1..255){
            print "nslookup $scope.$number\n";
         }

 modifying the control variable modifies the element of
  the array
         foreach $line (@file){
             chomp($line);
             $line .= "\r\n";
         }
The Cryptic $_

the 'default variable' is $_
many Perl functions use the default
 variable
       foreach (20..30){
          if($_ % 2){ print; }
       }


How do you know if a function supports
 $_?
Reversing a list
 the reverse operator returns the reverse of a list or
  array
 doesn't alter the original
   @numbers = (1..5);
   @numbers = reverse @numbers; # good
   reverse @numbers; # still reversed
   print reverse @numbers; # prints in increasing order



 reverse alone isn't very useful, and -w lets us know
   Useless use of reverse in void context at
   scriptname line line_number
Sorting it all out
 The sort operator returns the sorted version of
  a list or array
 It sorts 'ASCIIbetically'
 This operator also doesn’t modify the original list
  or array
 The warning flag/pragma can also generate a
  useful message about useless use of sort in a
  void context
     @sorted = sort qw( quarterly_report.txt
                        graph.jpg johnson.eml );
     print "@sorted\n";

     graph.jpg johnson.eml quarterly_report.txt
 Context
  Page 51 of the Llama book says this is the most important concept
   of the entire book!
  Scalar context - Perl expects a scalar value as a result of an
   expression

$a = $b; #simple example of a scalar assignment
$list[$a] = $b; #also scalar assignment
$number **= $exponent; #binary assignment is scalar context


  List context - Perl expects a list value as a result of an expression
@a = @b; #simple list assignment
($a, $b, $c) = qw/ ay bee see /; #also list context
foreach $name (@name_list){ #list context without assignment

 **Page 53 of the Llama book has some better examples
Lists in scalar context
 Using a list in scalar context is a kind of depends
 Assigning an array to a scalar stores its size

    @a = (1..4); #create a 4 element list
    $s = @a; #store the size of the list in $s
    print "Size: $s "; #print the size of the list
    print "Index: $#a\n"; #print the last index

    Size: 4 Index: 3

 The scalar function forces a list or array into scalar
  context

    print scalar @a, "\n"; #print the size of @a
Scalars in list context

This is much more straightforward: when a
 scalar is used in list context it is treated as
 a list containing one item

@name_list = 'joe'; #a list of one
foreach $name ('joe'){ print $name; } #list of one again
<STDIN> in list context
 The diamond operator will return everything until
  End Of File (EOF) in list context
 Each item (delimited by a newline) represents 1
  element in the resulting list
 EOF from the keyboard in UNIX is CTL-D
   @input_list = <STDIN>; #list context


 removing the new lines couldn't be easier
   chomp(@input_list = <STDIN>); #chomp „em all!
 Interesting comments from the Llama
Page 46: “… a beginning Perl programmer (wanting to see
how Perl‟s speed compares to C‟s) will take, say, a
sorting algorithm optimized for C (with many array index
operations), rewrite it straightforward in Perl (again,
with many index operations) and wonder why it‟s so slow.
The answer is that using a Stradivarius violin to pound
nails should not be considered a sound construction
technique.”



Page 55: “… Perl will generally waste memory to save time.
This is a good tradeoff; if you‟re short of memory, you
can buy more; if you‟re short on time, you‟re hosed.”

								
To top