in reply to nested maps

map { my $x = $_; map { $x . $_ } @a; } @a;

Nasty temporary variableses! NestedMap

Replies are listed 'Best First'.
Re^2: nested maps
by raygun (Scribe) on Sep 20, 2020 at 00:25 UTC
    But if there's only one such construction in a Perl program, which approach incurs more overhead?
    • the single nasty temporary variable, or
    • loading a CPAN module that is used only once, to replace that variable with, to be frank, somewhat clunky syntax for accessing the outer $_ in the inner map
    And are there two different answers if you define "overhead" in terms of the burden on Perl versus the burden on the human brain reading the code? (To reduce brain overhead, at least the temporary variable can be given a meaningful name, whereas the NestedMap::stack[] syntax is inherently meaningless as well as kind of ugly.)
      I'd define my own custom sub cross(&@@) sub cross(&\@\@) which does the "nasty" stuff in the inside after calling cross {$a.$b} @a,@a

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery

        OK, my prototype wasn't totally correct.

        Here an implementation allowing to combine multiple cross(), like in the OP

        use strict; use warnings; use Data::Dump qw/pp dd/; use 5.12.0; # https://perlmonks.org/?node_id=11121968 sub cross(&\@@) { my ( $code, $a_a, @b ) = @_; #warn pp $code, $a_a,\@b; map { $a = $_; map { $b=$_; &$code } @b; } @$a_a; } my @a = 1..3; my @b = 4..6; my @c = 7..9; pp cross { $a.$b } @a, cross { $a.$b } @b,@c;

        ( 147, 148, 149, 157, 158, 159, 167, 168, 169, 247, 248, 249, 257, 258, 259, 267, 268, 269, 347, 348, 349, 357, 358, 359, 367, 368, 369, )

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery