Learning Perl Objects, References & ModulesLearning Perl Objects, References & ModulesSearch this book

3.5. Modifying the Array

You've seen how to solve the excessive copying problem with an array reference. Now let's look at modifying the original array.

For every missing provision, push that provision onto an array, forcing the passenger to consider the item:

sub check_required_items {
  my $who = shift;
  my $items = shift;
  my @required = qw(preserver sunscreen water_bottle jacket);
  my @missing = ( );

  for my $item (@required) {
    unless (grep $item eq $_, @$items) { # not found in list?
      print "$who is missing $item.\n";
      push @missing, $item;
    }
  }

  if (@missing) {
    print "Adding @missing to @$items for $who.\n";
    push @$items, @missing;
  }
}

Note the addition of the @missing array. If you find any items missing during the scan, push them into @missing. If there's anything there at the end of the scan, add it to the original provision list.

The key is in the last line of that subroutine. You're dereferencing the $items array reference, accessing the original array, and adding the elements from @missing. Without passing by reference, you'd modify only a local copy of the data, which has no effect on the original array.

Also, @$items (and its more generic form @{$items}) works within a double-quoted string. Do not include any whitespace between the @ and the immediately following character, although you can include nearly arbitrary whitespace within the curly braces as if it were normal Perl code.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.