Chinaunix首页 | 论坛 | 博客
  • 博客访问: 835873
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-10-20 13:31:43

\@skipper, the result is a reference to that array. A reference to the array is like a pointer: it points at the array, but it is not the array itself.

A reference fits wherever a scalar fits. It can go into an element of an array or a hash, or into a plain scalar variable, like this:

  1. my $reference_to_skipper = \@skipper;

Because we can copy a reference, and passing an argument to a subroutine is really just copying, we can use this code to pass a reference to the array into the subroutine:

  1. my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
  2. check_required_items("The Skipper", \@skipper);
sub check_required_items { my $who = shift; my $items = shift; my @required = qw(preserver sunscreen water_bottle jacket); for my $item (@required) { unless (grep $item eq $_, @{$items}) { # not found in list? print "$who is missing $item.\n"; } } }

in the above case, the dereference array can be written like @$items.

Now $items in the subroutine is a reference to the array of @skipper.

Dereferencing the Array Reference

That is, wherever we write skipper to name the array, we use the reference inside curly braces: { $items }. For example, both of these lines refer to the entire array:

@ skipper @{ $items } #the $items is a reference to array.

whereas both of these refer to the second item of the array:
$ skipper [1] ${ $items }[1]
  1. #!/usr/bin/perl -w
  2. #
  3. use strict;

  4. my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
  5. check_required_items('The Skipper', \@skipper);

  6. sub check_required_items{
  7. #my $who = shift;
  8. #    my $items = shift;
  9.     my @required = qw(preserver sunscreen water_bottle jacket);

  10.     foreach my $item (@required){
  11.         unless( grep $item eq $_, @{$_[1]}){
  12.             print "$_[0] missing $item\n";
  13.         }
  14.     }
  15. }








阅读(624) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~