in reply to Creating X BitMap (XBM) images with directional gradients

Interesting variant of a switch statement in orient_matrix(). I don't believe i've seen that construct before.

Thanks!

perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'

Replies are listed 'Best First'.
Re^2: Creating X BitMap (XBM) images with directional gradients
by kcott (Archbishop) on May 22, 2021 at 07:31 UTC

    G'day cavac,

    Sorry for the slow response: I've been unwell recently and haven't logged in for a few days.

    "I don't believe i've seen that construct before."

    I'm fairly certain I first saw that type of construct in the original Camel Book back in the '90s; I use it occasionally when it seems appropriate. There's currently similar code in "perlsyn: Basic BLOCKs".

    The code in "perlsyn: Switch Statements" does much the same thing; however, I don't use the experimental given/when (switch) feature.

    Anyway, thanks for looking and leaving a comment (++).

    — Ken

      Another Way To Do It™ (tested and works):
      my %DISPATCH_TABLE; BEGIN { %DISPATCH_TABLE = ( n => sub { my ($oriented, $matrix) = @_; push $oriented->@*, $matrix->[$_] for reverse 0 .. $matrix->$#*; }, s => sub { my ($oriented, $matrix) = @_; push $oriented->@*, $matrix->[$_] for 0 .. $matrix->$#*; }, e => sub { my ($oriented, $matrix) = @_; for my $x (0 .. $matrix->$#*) { push $oriented->@*, my $col = []; for my $y (0 .. $matrix->[$x]->$#*) { push $col->@*, $matrix->[$y][$x]; } } }, w => sub { my ($oriented, $matrix) = @_; for my $x (0 .. $matrix->$#*) { push $oriented->@*, my $col = []; for my $y (reverse 0 .. $matrix->[$x]->$#*) { push $col->@*, $matrix->[$y][$x]; } } }, ); } sub orient_matrix { my ($orient, $matrix) = @_; my $code = $DISPATCH_TABLE{$orient} or die "Unknown orientation '$orient'"; $code->(my $oriented = [], $matrix); return $oriented; }

      Uhm, seems like i must have skipped (or since forgotten) a few chapters.

      That's the really nice thing in Perl. "No matter what it is, you can use it in a boolean expression"

      perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'