Search code examples
arraysperlhashtable

Error In Finding Number of Elements In Array (Perl)?


I am trying to write a program in Perl to find the number of elements in an array. (This array is supposed to be made up of files with ".txt" extension in the current directory. I then plan on using this array to read all ".txt" files into a hash.) However, I keep getting an array size = 0. I know that I have over eight ".txt" files in my directory, so wouldn't I have over eight array elements?

My program is as follows:

    #!/user/bin/perl
    my $readfdir = '.';
    opendir(DIR, $readfdir) or die $!;
    my @readf = glob(".*.txt");
    my $arrSize = @readf;
    print "array size = $arrSize\n";

Solution

  • Your glob is most likely not what you think

    my @readf = glob(".*.txt");
    

    You are using what looks like a regex syntax, i.e. .* to match any string, but in a glob, that is *. So it should be:

    my @readf = glob("*.txt");
    

    Also, your opendir statement is quite redundant if you use a glob instead. Use either opendir/readdir OR a glob.