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

I am trying to test if there is any .txt file existed in my directory. I use " if (-e *.txt) ", it doesn't give me right result. So how to make the wildcard '*' work with the file testing operator ?
  • Comment on how to make wildcard work in if (-e *..)

Replies are listed 'Best First'.
Re: how to make wildcard work in if (-e *..)
by BazB (Priest) on May 16, 2002 at 19:07 UTC

    glob makes perl expand filenames with wildcards, just as the shell would, but I'm not sure if it'll do the trick here.

    An alternative is to use something like:

    opendir(DIR, "dir") or die "$!"; my @txt_files = grep {/\.txt$/} readdir(DIR); if (scalar @txt_files > 0) { #do stuff }

    Cheers.

    BazB

    Update: Ooops. Fixed misplaced bracket.

Re: how to make wildcard work in if (-e *..)
by jsprat (Curate) on May 16, 2002 at 19:07 UTC
    Wildcards won't work with the filetest operator. Try readdir and grep, ie:
    opendir DIR, '.' or die "Error: $!"; my @files = grep { /\.txt$/ } readdir DIR;
    will find *.txt in the current directory.
Re: how to make wildcard work in if (-e *..)
by tachyon (Chancellor) on May 16, 2002 at 19:56 UTC

    print "Found textfile!" if <$dir/*.txt>

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

      Beware that this executes the glob in a scalar context, which will really confuse you when you reexecute the code, since a scalar glob has local magical state. For example, run:
      foreach $n (1..50) { print "$n: "; print "yes" if -e <*>; print "\n"; }
      If you have seven files, every 7th number will be missing, because the glob has run out, and has returned undef, and is resetting.

      This is better, as it uses glob in a list context:

      print "Found textfile!" if () = <$dir/*.txt>;

      -- Randal L. Schwartz, Perl hacker

Re: how to make wildcard work in if (-e *..)
by derby (Abbot) on May 16, 2002 at 19:54 UTC
    or if you're wed to the glob:

    map { $txt = 1 if -e } <*.txt>;

    -derby