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

Hi, why am I getting the following warning when the below piece of code is getting executed?

Use of uninitialized value in concatenation (.) or string at perl.pl line 216, <$file> line 18.

my $file; my @files; open $file, '<',"$options{c}" or die "could not open '$file' $!\n" +; @files = <$file>;
  • Comment on Use of uninitialized value in concatenation (.) or string at perl.pl line 216, <$file> line 18.
  • Download Code

Replies are listed 'Best First'.
Re: Use of uninitialized value in concatenation (.) or string at perl.pl line 216, <$file> line 18.
by chrestomanci (Priest) on Dec 15, 2010 at 10:33 UTC

    From your code, it looks like $options{c} contains the filename you want to read from, and $file is your file handle.

    If the open fails for any reason, then the filehandle stored in $file will be undefined, but you are attempting to include it in the die error message.

    In your die error message, you have said 'open', I suggest you change that to 'read from' so that the end user knows what the script it trying to do. Also, there is a feature of the die command, where if the die string is terminated with a newline, it is output literally, but if you omit the new line, you get the line number as well, which is helpful for debugging.

    Line 3 of your code should probably read:

    open $file, '<', $options{c} or die "could not read from '$options{c}' + $!";
Re: Use of uninitialized value in concatenation (.) or string at perl.pl line 216, <$file> line 18.
by ELISHEVA (Prior) on Dec 15, 2010 at 10:26 UTC

    Unless Perl is lying to you one of the following three variables is undefined $file, the value assigned to 'c' in your %options hash (i.e. $options{c}), or $!. If this is indeed your code, I'd lay bets on $file as you declared it but never gave it a value.

Re: Use of uninitialized value in concatenation (.) or string at perl.pl line 216, <$file> line 18.
by fisher (Priest) on Dec 15, 2010 at 10:31 UTC
    try this:
    my $file; my @files; open $file, '<', "$options{c}" or die "could not open \"$options{c +}\": $!"; @files = <$file>;
    self-explanatory code, isn't it?
Re: Use of uninitialized value in concatenation (.) or string at perl.pl line 216, <$file> line 18.
by Anonymous Monk on Dec 15, 2010 at 11:06 UTC
    If you use autodie you won't have to add or die or get confused about which variable contains the filename (which, FWIW, we discussed this on december 3rd) :)
    use autodie; open my $file , '<', $options{c}; my @files = <$file>; close $file;