Search code examples
regexperlbackticksexitstatus

Perl: suppress output of backtick when file not found


In my code :

$status = `ls -l error*`;

It shows output : ls *error No such file or directory. How can I suppress this message. I am interested in determining that the error files are generated or not. If yes, I need the list of files else ignore (without printing the message)


Solution

  • By running it like

    $status = `ls -l error* 2> /dev/null`;
    

    and suppressing the external command's output to standard error.

    If you just need the file names (and not all the other info that ls's -l switch gives you), this can be accomplished in pure Perl with a statement like

    @files = glob("error*");
    if (@files == 0) { 
        ... there were no files ...
    } else { 
        ... do something with files ...
    }
    

    and if you do need all the other info you get from ls -l ..., applying the builtin stat function to each file name can give you the same information.