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

Hi,

How can I check if directory existing using regexp? I have 2 variables include part of the dir. name:

$stream = 241 $version = 73

The Dir Name is: 241.73_Dir_Name

And I want to check if that directory exists, somting like:

if ( -d "$stream.$version\_\w*/") ...

Please advice,

Thanks.

Replies are listed 'Best First'.
Re: Check if dir exist using regexp
by Fletch (Bishop) on Nov 20, 2007 at 16:01 UTC

    -d doesn't work that way. You're either going to have to manually grobble through the list of files in the containing directory (using opendir and readdir), or possibly use glob instead of a regular expression.

    (And please use proper <code></code> tags and lose the angry fruit salad coloring.)

    Update: And the angry fruit salad coloring tags were removed and there was much rejoicing. Just remember, the retinas you save could be your own . . .

Re: Check if dir exist using regexp
by johngg (Canon) on Nov 20, 2007 at 16:03 UTC
    You can't use a regex in that context. If the name has the literal "_Dir_Name" at the end you can disambiguate the $version from the "_Dir_Name" like this.

    if ( -d "$stream.${version}_Dir_Name" ) { ... }

    If you have more than one possible directory that you are trying to match then you could look at opendir / readdir or, perhaps, glob and filter out what you want with grep.

    I hope this is of use.

    Cheers,

    JohnGG

Re: Check if dir exist using regexp
by tuxz0r (Pilgrim) on Nov 20, 2007 at 16:59 UTC
    Do you need to recursively look for those style of directory names? If not, then using a a simple grep combined with glob should work fine. Otherwise, File::Find is your best bet to do recursive searching.
    $s = 241; $v = 73; @found = grep { -d $_ && m/$s\.$v_\w+/ } glob "/some/dir/*"; # DO STUFF WITH @found matches

    ---
    echo S 1 [ Y V U | perl -ane 'print reverse map { $_ = chr(ord($_)-1) } @F;'
    Warning: Any code posted by tuxz0r is untested, unless otherwise stated, and is used at your own risk.

Re: Check if dir exist using regexp
by perlfan (Parson) on Nov 20, 2007 at 16:01 UTC
    I think File::Find has this capability, otherwise you could use File::Find, then filter the directories found with Perl's grep.
Re: Check if dir exist using regexp
by olus (Curate) on Nov 20, 2007 at 16:06 UTC
    Something like this might work
    openddir(DIR, $rootDir); @sub_dirs = readdir(DIR); closedir(DIR); foreach my $d (@sub_dirs) { if( $d =~ / regexp / ) { # you found your dir last; } }

    --
    olus