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

I have a the following line in my code,glob to find out .ntp file in a directory and I do an error check if the file is not found ,I keep getting the below warning ,how do I overcome this?

$file = glob(($dir . '\\files\\*.ntp')) or die "no NTP file\n" if( not + defined( $file ));

Warning:- Value of glob construct can be "0"; test with defined() at perl.pl line 65.

Replies are listed 'Best First'.
Re: Glob error check giving warning
by ysth (Canon) on Dec 05, 2010 at 08:38 UTC
    By and large, don't use glob() in scalar context. The next time your program executes that line, it will provide the next *.ntp file from the original directory, even if $dir has changed, and after getting each *.ntp file, it will return undef once before restarting. Try this instead.
    if ( ! defined( $file ) ) { $file = ( glob(...) )[0]; if ( ! defined( $file ) ) { die "no NTP file\n"; } }
    --
    A math joke: r = | |csc(θ)|+|sec(θ)|-||csc(θ)|-|sec(θ)|| |
    Online Fortune Cookie Search
    Office Space merchandise
Re: Glob error check giving warning
by CountZero (Bishop) on Dec 05, 2010 at 08:05 UTC
    This will work:
    use Modern::Perl; my $dir = 'C:/data'; my $file = glob(($dir . '/books/*.pdf')) // die "no PDF file\n"; say $file;
    The // or defined or operator is available since Perl 5.10.

    One more hint: use forward slashes in your filepaths: those need not be escaped, even on Windows.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Glob error check giving warning
by Anonymous Monk on Dec 05, 2010 at 02:26 UTC
    $ echo Value of glob construct can be "0"; test with defined() at perl +.pl line 65. |splain Value of glob construct can be "0"; test with defined() at perl.pl lin +e 65. (#1) (W misc) In a conditional expression, you used <HANDLE>, <*> (glob +), each(), or readdir() as a boolean value. Each of these constructs can return a value of "0"; that would make the conditional express +ion false, which is probably not what you intended. When using these constructs in conditional expressions, test their values with the defined operator.