刚开始学习perl大约三天前.
我有一个字符串数组,我从文本文件加载:
my @fileContents;
my $fileDb = 'junk.txt';
open(my $fmdb, '<', $fileDb);
push @fileContents, [ <$fmdb> ];
Run Code Online (Sandbox Code Playgroud)
该文件已知长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).
Run Code Online (Sandbox Code Playgroud)
打印出数组的内容并将其与输入文件匹配,验证数组是否正确加载(甚至将输出重定向到文件并使用diff来与输入文件进行比较并且它们匹配),但我仍然不能获取数组大小(文本行数).
我的猜测是,必须访问$ fileContents作为一个二维数组与它有关.我最初期望能够说"print $ fileContents [$ i];" 但那没用; 我需要在[$ i]之前插入[0].我真的不明白为什么会这样.
有人可以帮助我理解为什么数组大小不起作用,以及如何在这种情况下以正确的方式做到这一点?
您似乎将整个文件加载到数组引用中,并将数组引用存储在数组中,然后检查数组的大小,当然它是1.
push @fileContents, [ <$fmdb> ];
# ^---------^--- creates array ref
Run Code Online (Sandbox Code Playgroud)
你想要的是:
push @fileContents, <$fmdb>;
Run Code Online (Sandbox Code Playgroud)
或者为什么不呢
@fileContents = <$fmdb>;
Run Code Online (Sandbox Code Playgroud)
如果你有一个多维数组,并且想要检查其中一个内部数组的大小,你要做的是首先正确地取消引用它:
my $size = @{ $fileContents[0] }; # check size of first array
Run Code Online (Sandbox Code Playgroud)
要清楚,你所做的是这样的:
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
Run Code Online (Sandbox Code Playgroud)