初めてのPerl 第4章 練習問題4

初めてのperl 第4章 練習問題4

use strict;
use warnings;
use Data::Dumper;

use 5.010;

# 入力された名前に対して、挨拶の処理を実行する。
sub greet{
  my $name = shift @_;
  state @members;

  #挨拶
  print "Hi ";

  # 名前を表示させる
  print $name . "!";

  # 最初に来たら「you~」のメッセージを出す。
  # 二回目にきた人には「also~」を出す。

  if($#members == -1){
    print "you are the first one here! \n";
  }else{
    # @membersに格納されている名前を表示させる。
    foreach my $name(@members){
      print $name . " is also here!";
    }
  }
  #次に来た時のために名前を格納する。
  push(@members, $name);
}

greet("mike");
greet("fred");

以下、実行結果となります。

Hi mike!you are the first one here!
Hi fred!mike is also here!