[perl] 続・初めてのPerl 第4章 「リファレンス入門」

練習問題の回答をメモ。

ex04-2
#!/usr/bin/perl
use strict;

my @gilligan = qw(red_shirt hat lucky_socks water_bottle);
my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
my @professor = qw(sunscreen water_bottle slide_rule batteries radio);


my %all = (
  Gilligan => \@gilligan,
  Skipper => \@skipper,
  Professor => \@professor,
);

&check_items_for_all(\%all);

sub check_items_for_all {
  my $all_hash_ref = shift @_;
  foreach  my $crew (sort keys %$all_hash_ref) {
    my $crew_array_ref = $all_hash_ref->{$crew};
    &check_required_items($crew, $crew_array_ref);
  }
}

sub check_required_items {
  my $who = shift;
  my $items = shift;

  my @required = qw(preserver sunscreen water_bottle jacket);
  my @missing = ( );

  foreach my $item (@required) {
    unless (grep $item eq $_, @$items) {
      print "$who is missing $item.\n";
      push @missing, $item;
    }
  }
  if (@missing) {
    print "Adding @missing to @$items for $who.\n";
    print "\n";
    push @$items, @missing;
  }
}

長くみえるけど、実際に自分で考えたのは &check_items_for_all だけ。
そういえば、Perl に C みたいなポインタ演算は無いのかな?だからわざわざリファレンス(参照)という言葉を使ってるのかな?

追記(2007年12月8日)

Perl ではポインタ演算や、メモリを直接に割り当て/開放することは無いらしい。だから、すべてのリファレンスは常に有効な値を持っている。(初めてのPerl p.358〜p.359)確かにこれだったら「ポインタ」の変わりに常に何かを参照しているという意味で「参照」という言葉を使ったほうが自然かも。

反省点

リファレンスはデータ構造同士のつながりを表現するためのもの(でいいのかな?)だから、その関係を絵でイメージできることが大事だよ。