1

我正在尝试编写一个 Perl 函数,该函数接受两个列表/数组并计算它们的叉积(笛卡尔积)。我目前有代码可以使用两个输入列表并计算叉积,但是我在打印嵌套列表时遇到了麻烦。

我正在寻找有关打印嵌套列表的最佳方法的建议。这是我目前的尝试:

for(@C) { 
    for(@$_) { 
        print $_; 
    } 
    print " ";
}

# prints
# 1A 1B 1C 1D 1E 1F 1G 1H 1I 
# 2A 2B 2C 2D 2E 2F 2G 2H 2I 
# 3A 3B 3C 3D 3E 3F 3G 3H 3I 
# 4A 4B 4C 4D 4E 4F 4G 4H 4I 
# etc ... 

但这对我来说看起来不够珀利。所以我再次尝试map

print map { 
    map { $_ } @$_; 
} @C;

# prints
# 1A1B1C1D1E1F1G1H1I
# 2A2B2C2D2E2F2G2H2I
# 3A3B3C3D3E3F3G3H3I
# 4A4B4C4D4E4F4G4H4I
# etc ... 

但物品都压在一起。无论如何要格式化这种方法map吗?有没有更好的方法来实现这一点?

完整功能代码:

use strict;
use warnings; 

# globals
my @digits  = (1,2,3,4,5,6,7,8,9);
my @letters = ("A","B","C","D","E","F","G","H","I");
my @rows = @digits;
my @cols = @letters;
my @squares = cross(\@rows, \@cols);

sub cross {
    my @C = [];

    foreach (reverse @_) {
        my @A = @$_;

        @C = map { my $n = $_; map { [ $n, @$_ ] } @C } @A;
    }

    # works
    #for(@C) { 
    #   for(@$_) { 
    #       print $_; 
    #   } 
    #   print " ";
    #}

    print map { 
        map { $_ } @$_; 
    } @C;

    return @C;
}
4

3 回答 3

3

没有什么说map不能返回格式化的字符串:

print map { " $_" };

或者为了更精确的控制,使用join:

print join ' ', map { ... };
于 2013-05-25T22:49:52.523 回答
3
print map { join '', @$_, ' ' } @C;
于 2013-05-25T22:53:00.313 回答
0

By default arrays interpolate into strings as you want them here. So:

#! /usr/bin/env perl
use common::sense;

my @a = ([qw/1A 1B 1C 1D 1E 1F 1G 1H 1I/],
         [qw/2A 2B 2C 2D 2E 2F 2G 2H 2I/],
         [qw/3A 3B 3C 3D 3E 3F 3G 3H 3I/],
         [qw/4A 4B 4C 4D 4E 4F 4G 4H 4I/],
         ['etc', '...']);

say "# prints";
say "# @$_" for @a;

Outputs:

# prints
# 1A 1B 1C 1D 1E 1F 1G 1H 1I
# 2A 2B 2C 2D 2E 2F 2G 2H 2I
# 3A 3B 3C 3D 3E 3F 3G 3H 3I
# 4A 4B 4C 4D 4E 4F 4G 4H 4I
# etc ...

Alternatively,

local $" = ', ';
say "# @$_" for @a;

Outputs:

# 1A, 1B, 1C, 1D, 1E, 1F, 1G, 1H, 1I
# 2A, 2B, 2C, 2D, 2E, 2F, 2G, 2H, 2I
# 3A, 3B, 3C, 3D, 3E, 3F, 3G, 3H, 3I
# 4A, 4B, 4C, 4D, 4E, 4F, 4G, 4H, 4I
# etc, ...
于 2013-05-26T02:51:56.843 回答