t-rex has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I want to test if a file with name tpsm exists, and my folder might contain many file such as

tpsm_01 tpsm_12 tpsm_23 . . . and so on

the above code didnt work as i didnt have exact file name , on the shell we can directly use file* to check for multiple files with the same name ( some part of the name) but how fdo i check here?

basically i want to test if a file with name tpsm _x exists or not, i don't know what will be the value of x , but i just want to know if files having such names are there or not. i tried with

$pwd = $ENV{'PWD'}; $file = "$pwd/tpsm*"; if (-e $file) { #do something }

please let me know how can i achieve this

i am using glob and its working fine , thanks @Corion and @steveib

Replies are listed 'Best First'.
Re: finding a file exist amongst many files
by stevieb (Canon) on Aug 25, 2016 at 14:07 UTC
    File::Find::Rule works wonders for doing these tasks. It allows you to supply regexes as the filenames you're looking for.

    use warnings; use strict; use File::Find::Rule; my $dir = 'test'; my @files = File::Find::Rule->file ->name('tpsm_*') ->in($dir); for (@files){ print "$_\n"; }

    In a test/ directory, I've got:

    blah.txt tpsm.txt tpsm_10.txt tpsm_4.txt

    Here's the output of files found matching the name I've sent in to look for:

    test/tpsm_10.txt test/tpsm_4.txt

      thanks for the reply steve. basically i am looking for if a file with tpsm_x exists, so on the shell it is pretty easy to find this. i want to know its perl counterpart, nevertheless i can try this but i don't want to install this package(legacy code issues).

        Take two, with builtins only. Note that with readdir, it doesn't keep the whole path, so you have to add it back manually:

        use warnings; use strict; my $dir = 'test'; opendir my $dh, $dir or die $!; while (readdir $dh){ if (/tpsm_.*/ && -f "$dir/$_"){ print "$dir/$_ is a file\n"; } }

        update: or use glob as Corion said :)

      Hello Steve, I just came to know of the requirement and we shall need to process these file , so i was thinking to write a perl sub for iterating through all these files in the manner you have gone through, but without the package Find::Rule, could share a snippet for the same?

Re: finding a file exist amongst many files
by Marshall (Canon) on Aug 25, 2016 at 16:53 UTC
    Here is perl doc for glob. Readdir is as stevieb points out is also an option. note that bsd_glob see File::Glob has slightly different rules than the built-in glob.
    my @perl = <*.pl>; print scalar @perl;
    Would print number of .pl files in current directory.