Perl: Ways to determine the size of a string array don't seem to work

Just started learning perl about three days ago.

I have an array of strings loaded from a text file like this:

my @fileContents;
my $fileDb = 'junk.txt';
open(my $fmdb, '<', $fileDb);
push @fileContents, [ <$fmdb> ];

It is known that the file has a length of 1205 lines, but I can not get the size of the array, i.e. the number of rows loaded into the array.

I tried three different methods, described here and in other sections, on how to determine the number of elements in an array of strings and cannot make them work.

Below is my code commented out to include three different ways I found in my research to find the number of elements in an array.

#!/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];" ; [0] [$ i]. , .

- , ?

+4
1

, , , , 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
+5

All Articles