三天前刚开始学习perl。
我有一个字符串数组,我从文本文件加载:
my @fileContents;
my $fileDb = 'junk.txt';
open(my $fmdb, '<', $fileDb);
push @fileContents, [ <$fmdb> ];
已知文件长1205行但我无法检索数组的大小,即加载到数组中的行数。
我在这里和其他地方尝试了三种不同的方法,关于如何确定字符串数组中的元素数量,并且似乎无法使它们中的任何一个起作用。
以下是我的代码,评论包括我在研究中发现的三种不同方式,以查找数组中元素的数量。
#!/usr/bin/perl
#
# Load the contents of a text file into an array, one line per array element.
# Standard header stuff.
# Require perl 5.10.1 or later, and check for some typos and program errors.
#
use v5.10.1;
use warnings;
use strict;
# Declare an array of strings to hold the contents of the files.
#
my @fileContents;
# Declare and open the file.
#
my $fileDb = 'junk.txt'; # a 1205-line text file
open(my $fmdb, '<', $fileDb) or die "cannot open input file $!";
# Get the size of the array before loading it from the file.
# That size should be zero and is correctly reported as such.
#
my $sizeBeforeLoading = @fileContents;
say "size of fileContents before loading is $sizeBeforeLoading.";
# Load the file into the array then close the file.
#
push @fileContents, [ <$fmdb> ];
close( $fmdb );
# Now the array size should be 1205 but I can't get it to report that.
# Tried it three different ways.
my $sizeAfterLoading = @fileContents;
say "size of fileContents after loading is $sizeAfterLoading.";
#
# That didn't work; it reports a size of 1 when the real size is known to be 1205.
#
# Tried this:
$sizeAfterLoading = scalar @fileContents;
say "size of fileContents after loading is $sizeAfterLoading.";
#
# This one reported a size of 1.
$sizeAfterLoading = $#fileContents + 1;
say "size of fileContents after loading is $sizeAfterLoading.";
#
# This one reported an index of 0 for a size of 1.
# The real size is known to be 1205 so hard-code one less than that here
#
$sizeAfterLoading = 1204;
say "The file contents are:";
foreach my $i( 0..$sizeAfterLoading )
{
print $fileContents[ 0 ][ $i ];
}
#
# The contents of the fileContents array prints out correctly (all 1205 lines of text).
打印出数组的内容并将其与输入文件匹配,验证数组是否正确加载(甚至将输出重定向到文件并使用diff来与输入文件进行比较并匹配),但我仍然无法获得数组大小(文本行数)。
我的猜测是,必须访问$ fileContents作为二维数组与它有关。我最初期望能够说“print $ fileContents [$ i];”但那没用;我需要在[$ i]之前插入[0]。我真的不明白为什么会这样。
有人可以帮助我理解为什么数组大小不起作用,以及如何在这种情况下以正确的方式做到这一点?
答案 0 :(得分:5)
您似乎将整个文件加载到数组引用中,并将数组引用存储在数组中,然后检查数组的大小,当然它是1。
push @fileContents, [ <$fmdb> ];
# ^---------^--- creates array ref
你想要的是:
push @fileContents, <$fmdb>;
或者为什么不
@fileContents = <$fmdb>;
如果你有一个多维数组,并且想要检查其中一个内部数组的大小,你要做的是首先正确地取消引用它:
my $size = @{ $fileContents[0] }; # check size of first array
要说清楚,你所做的是:
my @file = <$fmdb>; # store file in array
my @fileContent = \@file; # store array in other array
my $size = @fileContent; # = 1 only contains one element: a reference to @file