Groups | Search | Server Info | Login | Register


Groups > tw.bbs.comp.lang.perl > #31

PerlX::ScopeFunction 0.03 釋出

From Kang-min Liu <gugod@gugod.org>
Newsgroups tw.bbs.comp.lang.perl
Subject PerlX::ScopeFunction 0.03 釋出
Date 2023-03-17 09:29 +0900
Organization A noiseless patient Spider
Message-ID <86cz58usn5.fsf@alpiner.steamdeck> (permalink)

Show all headers | View raw


https://metacpan.org/release/GUGOD/PerlX-ScopeFunction-0.03

好幾年前我擅自開始把 PerlX:: 這個 namespace 當成是「Perl 語言的延伸」的
意義在使用,並且做了一些有的沒的新語法。最近這星期做了 PerlX::ScopeFunction。

這個模組提供兩個新的語法關鍵字: let 與 with。

先看範例,就能大致上掌握這兩個關鍵字的用法:

    use v5.36;
    use List::Util qw( sum0 );
    use List::MoreUtils qw( part minmax );
    use PerlX::ScopeFunction qw(let with);

    my @input = (3,1,3,3,7);

    let ( ($min,$max) = minmax(@input); $mean = sum0(@input)/@input ) {
        say "$min <= $mean <= $max";
    }

    with ( part { $_ % 2 } @input ) {
        my ($evens, $odds) = @_;
        say "There are " . scalar(@$evens) . " even numbers: " . join(" ", @$evens);
        say "There are " . scalar(@$odds) .  " odd numbers: " . join(" ", @$odds);
    }

這兩個關鍵字提供了一種可以將幾個指定變數的語義範圍縮限起來的方式。前述範
例中 let 語句所造出的 $min、$max、$mean 三個變數的語義範圍是在後方的區塊
之內。with 語句則是能將一個算式取值,並把結果裝入 @_ ,使其能在後方的區塊內使
用。

這兩種語法結構都是從其他語言借過來的,在 Perl5 目前的語法中,最類似的是
sub closure 與 `do`:

    sub {
        my ($evens, $odds) = @_;

        ...
    }->(part { $_ % 2 } @input);


    do {
        my ($min,$max) = minmax(@input);
        my $mean = sum0(@input)/@input;

       ...
    };

而 PerlX::ScopeFunction 所做的就是提供一些新關鍵字,讓這種特殊片語寫起來
更加明瞭一些,也利於解讀。

----

Back to tw.bbs.comp.lang.perl | Previous | Next | Find similar


Thread

PerlX::ScopeFunction 0.03 釋出 Kang-min Liu <gugod@gugod.org> - 2023-03-17 09:29 +0900

csiph-web