Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!

I am trying to get rid of this warning and my question is how to avoid this:

Use of uninitialized value $array[0] in pattern match (m//) at ...

Here is the code I am trying to fix to avoid getting the uninitialized warnings:
... my $dir_txt_files = "stuff/"; tie my @array, 'Tie::File', $dir_text_files or die "Could not open fil +e '$dir_text_files' $!"; unshift @array, 'NAME, ADDRESS, ZIPCODE' unless $array[0] =~ /^[a-zA- +Z]/; # Remove any blank lines. @array = grep /\S/, @array; untie @array; ....
Thanks for looking!

Replies are listed 'Best First'.
Re: Use of uninitialized value in tie array
by Corion (Patriarch) on Apr 01, 2016 at 13:33 UTC

    Maybe the file is empty?

    Have you inspected how many elements there are in @array?

    On further inspection of your source code, the variable $dir_txt_files is named in a way that suggests that it is not a filename. This is furthered by you assigning it the value stuff/. But Tie::File wants a filename, not something else.

    Maybe you want to use glob or File::Find to find files?

      Its a file name. Yes, the file could be empty and thats where the issue occurs. Trying to figure it out a way to prevent it and how is the question.

        scalar @array gives you the number of elements in an array. if( @array ){ will also only be true if the array contains at least one element.

Re: Use of uninitialized value in tie array
by Anonymous Monk on Apr 02, 2016 at 02:49 UTC

    How about 'if (! defined $array[0])'?