2020年4月27日月曜日

開発環境

初めてのPerl 第7版 (Randal L. Schwartz(著)brian d foy(著)Tom Phoenix(著)近藤 嘉雪(翻訳)嶋田 健志(翻訳)、オライリージャパン)の4章(サブルーチン)、4.13(練習問題)4、5の解答を求めてみる。

コード

#!/usr/bin/env perl
use strict;
use warnings;
use v5.28;

say '4.';

sub greet {
    state $last;
    my ($name) = @_;
    print "Hi $name! ";
    if (defined $last) {
        say "$last is also here!";
    } else {
        say "You are the first one here!";
    }
    $last = $name;
}
greet('Fred');
greet('Barney');

say "5.";
sub greet_all {
    state @seen;
    my ($name) = @_;
    print "Hi $name! ";
    if (@seen) {
        say "I've seen: @seen"
    } else {
        say "You are the first one here!";
    }
    push @seen, $name;
}
for (qw(Fred Barney Wilma Betty)) {
    greet_all $_;
}

入出力結果(Zsh、PowerShell、Terminal)

% ./sample4.pl
4.
Hi Fred! You are the first one here!
Hi Barney! Fred is also here!
5.
Hi Fred! You are the first one here!
Hi Barney! I've seen: Fred
Hi Wilma! I've seen: Fred Barney
Hi Betty! I've seen: Fred Barney Wilma
%

0 コメント:

コメントを投稿