Mobile Factory Tech Blog

技術好きな方へ!モバイルファクトリーのエンジニアたちが楽しい技術話をお届けします!

Perlのコンテキストクイズにツールで答えてみた

はてなさんのコンテキストクイズに拙作のContextual-Diagで答えてみました。これでコンテキストマスターですね!?

github.com

use Test2::V0;
use CDD;

like(
    warnings { length( cdd ) },
    [qr/wanted SCALAR context/, qr/evaluated as STR/],
    'length <ここ> ... STR in SCALAR'
);

like(
    warnings { if( cdd ) {} },
    [qr/wanted SCALAR context/, qr/evaluated as BOOL/],
    'if (<ここ>) ... BOOL in SCALAR'
);

like(
    warnings { for my $i ( cdd ) {} },
    [qr/wanted LIST context/],
    'for my $i (<ここ>) ... LIST'
);

like(
    warnings {
        package Hoge {
            sub new { bless {}, $_[0] }
            sub hello {}
        }

        my $obj = Hoge->new;
        $obj->hello( cdd )
    },
    [qr/wanted LIST context/],
    '$obj->method(<ここ>) ... LIST'
);

like(
    warnings { my $x = cdd },
    [qr/wanted SCALAR context/],
    'my $x = <ここ> ... SCALAR'
);

like(
    warnings { my ($x) = cdd },
    [qr/wanted LIST context/],
    'my ($x) = <ここ> ... LIST'
);

like(
    warnings { my @y = cdd },
    [qr/wanted LIST context/],
    'my @y = <ここ> ... LIST'
);

like(
    warnings {
        my %hash = (
            key0 => 'hoge',
            key1 => cdd,
        )
    },
    [qr/wanted LIST context/],
    q!my %hash = ( key0 => 'hoge', key1 => <ここ> ); ... LIST!
);

like(
    warnings { scalar( cdd ) },
    [qr/wanted SCALAR context/],
    'scalar(<ここ>) ... SCALAR'
);

like(
    warnings { cdd },
    [qr/wanted VOID context/],
    '<ここ>; ... VOID'
);

# 注: sortの幾通りかの使い方を知っている前提で、テストしている
subtest 'sort <ここ>' => sub {

    # sort BLOCK LIST
    like(
        warnings { my @a = sort { cdd } ('a', 'b') },
        [qr/wanted SCALAR context/],
        'sort <ここ> / CASE: sort BLOCK LIST ... BLOCK context is SCALAR'
    );

    # sort SUBNAME LIST
    like(
        warnings { my @a = sort cdd ('a', 'b') },
        [qr/wanted SCALAR context/],
        'sort <ここ> / CASE: sort SUBNAME LIST ... SUBNAME context is SCALAR'
    );

    # sort LIST
    like(
        warnings { my @a = sort (cdd('a', 'b')) },
        [qr/wanted LIST context/],
        'sort <ここ> / CASE: sort LIST ... LIST'
    );
};

done_testing;