首页 > 解决方案 > Perl 从文件中打印二维矩阵

问题描述

所以我试图从一个文件中读取一个二维矩阵,这样我就可以将两个矩阵相乘。我可以打印矩阵的各个行,但我不能让子例程返回整个矩阵。我不确定我做错了什么。我从我正在使用的文件中粘贴了测试矩阵:

 12345                                                                              
 67890                                                                  
 34567                                                                    

我得到的输出是:

 final matrix is: ##THIS IS WHAT I AM TRYING TO PRINT OUT BUT I GET NOTHING
 row is:12345
 row is:67890
 row is:34567

标签: perlmatrixsubroutinefile-read

解决方案


这是一个例子:

use feature qw(say);
use strict;
use warnings;
use Data::Dumper;

{
    print "Enter filename: "; 
    chomp(my $matrix_file = <STDIN>);
    say "final matrix is:";
    my $matrix = matrix_read_file($matrix_file);
    print Dumper($matrix);
}

sub matrix_read_file {
    my ($filename) = @_;

    my @matrix;
    open (my $F, '<', $filename) or die "Could not open $filename: $!";
    while (my $line =<$F> ) {
        chomp $line;
        next if $line =~ /^\s*$/; # skip blank lines
        my @row = split /\s+/, $line;
        push @matrix, \@row;
    }
    close $F;
    return \@matrix;
}

如果您提供以下输入文件:

1 2 3 4 5
6 7 8 9 10

程序输出:

final matrix is:
$VAR1 = [
          [
            '1',
            '2',
            '3',
            '4',
            '5'
          ],
          [
            '6',
            '7',
            '8',
            '9',
            '10'
          ]
        ];

推荐阅读