Search code examples
perlgreppipels

Backticks in directory query generate problems with pipe


I'm trying to fill a Perl array with a list of file names in a directory,$dir, and I want to exclude directories. My code is:

my @lsArray = `ls -p $dir | grep -v '/$'`;

But it creates this error:

sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file

I cant seem to find a combination of quotes which does this correctly. Thanks....


Solution

  • Why are you using backticks for something that perl can do perfectly fine on its own?

    my @files = grep !-d, <$dir/*>;
    

    Btw, your error is that $' is a perl predefined variable (postmatch) that gets interpolated, so the closing ' is missing.

    If you had used

    use strict;
    use warnings;
    

    Perl would have told you what the problem was:

    Use of uninitialized value $' in quoted execution (``, qx) at ...
    

    Always use those two pragmas: Errors do not get less difficult to handle because you don't know about them.