perl - 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
解决方案
这是一个例子:
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'
]
];
推荐阅读
- java - 如何一次迭代 Stream 的两个项目?
- java - 我想使用 Jsoup 从整个在线词典中获取定义,我必须做些什么来防止我的 IP 被阻止?
- pointers - 如何使用指向字符串数组的指针而不进行强制转换
- python - 在 postgresql 中为 date_time 字段转换日期
- json - 如何在 Vue 中将 CSV 文件转换为 JSON
- spring-boot - 寻找一种在 docker bridge 网络中的 nginx 后面的多个容器化 Spring Boot 应用程序之间进行通信的方法
- python - 2d np数组上的Python numpy布尔掩码
- python - 退格并在python中的关键字前添加逗号
- angular - Angular11 - NG0303:无法绑定到“ngForOf”,因为它不是“tr”的已知属性
- flutter - Dart Flutter 中的嵌套 groupby