in reply to Can I get help with Perl glob for filtering a directory

Works for me if I use a metacharacter so there's a dynamic pattern rather than a fixed string to match against. However, I generally prefer Path::Tiny for anything even slightly complex in this regard. Here are both approaches illustrated:

#!/usr/bin/env perl use strict; use warnings; use autodie; use Test::More tests => 2; use File::Glob qw( :globally :nocase); use Path::Tiny; open my $foo, '>', '/tmp/MisterPerl'; print $foo "Yeah!\n"; close $foo; my (@f) = glob ('/tmp/misterper[l]'); is $f[0], '/tmp/MisterPerl', 'File found case-insensitively with File: +:Glob'; @f = path ('/tmp')->children (qr/^misterperl/i); is $f[0], '/tmp/MisterPerl', 'File found case-insensitively with Path: +:Tiny';

Meta note: this node was apparently posted OK but not attached to the thread and then the content disappeared (see Re: Missing 'in reply to...' And 'in thread....'). I've restored the content now.

Replies are listed 'Best First'.
Re^2: Can I get help with Perl glob for filtering a directory
by misterperl (Friar) on Nov 06, 2023 at 16:47 UTC
    Thanks all for the comments. I already read glob documentation,so that wasn't really helpful, and I don't recall anywhere that a wildcard was spcified there as required but perhaps.

    I'm trying to think of a SAFE way to wildcard the file and only get exact matches (except for case). I'm thinking maybe glob for

    myfilename*

    Then grep that list for files that match my original file length. Pretty tricky huh? I also read:

    https://metacpan.org/pod/Path%3A%3ATiny

    and ^F for "case" ; upper/lower didn't seem to be discussed at all.

    I'm thinking of just using something like the old reliable albiet fugly:

    my @f = grep /^\Q$fileName\E$/i,readdir D;

    This whole endeavor of asking this was to get more skilled with glob(). It seems strange to me that part of glob() functionality is to return a subset of the set of files in a dir. That's exactly what I want to do - just different than a partial filename? That's why glob() seemed like a more natural approach to this requirement.

    Larry said  Perl makes the difficult easy and the impossible possible. In this case, it seems it's making  Perl is making the easy, difficult! Just IMHO :)

    TY sirs and ladies..

      Grepping readdir seems pretty easy, aside from needing to opendir and check for errors, but the Path::Tiny ->children regex option is the easiest of all. Glob is easy if you want case-sensitive matches, which almost all Unix scripts would (the environment for which Perl was created). You also have the option of grepping glob, to save the opendir call:

      my @files= grep /\/\Q$fileName\E$/i, <$dirName/*>;

      but note that one important difference between glob and readdir is that glob will return the path portion as you specified it in the pattern.