Search code examples
regexperlglob

How to match digits in perl glob


$dir_path = (-d ("./abc/dir-\d.\d.\d")) ?
            glob("./abc/dir-\d.\d.\d/my-dir*") : "my-dir-doesnot-exists";

is this a valid glob option? can I use \d to match numbers in the dir path ?

$dir_path should get "./abc/dir-#.#.#/my-dir/some_dir_name" if "./abc/dir-#.#.#" exists (where # is any digit) else "my-dir-doesnot-exists" string


Solution

  • You're calling both instances of glob in scalar context (but not as an iterator) which is very wrong. For example,

     my $foo = glob("a");
     my $bar = glob("a");
     say $foo // "[undef]";    # a
     say $bar // "[undef]";    # [undef]
    

    The glob language is completely different than the regex language. \d won't work, but [0123456789] would.

    my @dir_paths = glob("./abc/dir-[0123456789].[0123456789].[0123456789]/my-dir*");
    
    die "No match!"         if !@dir_paths;
    die "Too many matches!" if @dir_paths > 1;
    
    my $dir_path = $dir_paths[0];