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

I am trying to see if a file exists in any permutation of case without having to get a directory listing. I guess an approach to -e that would have an i ( as in $string =~ /text/i ) effect. Thanks!

Replies are listed 'Best First'.
Re: Case insensitive file testing
by theorbtwo (Prior) on Aug 07, 2002 at 09:26 UTC

    Hm. See BUU for a simpler way to do it, but this seemed mildly interesting to me. This WTDI will produce a glob pattern that will match only the wanted files. (I'm currently on windows, so this will only ever give at most one filename, since the OS enforces case-insensitivity. This is, therefore, partaly tested.) Note that this won't work with real paths, only filenames, since the path seperator gets messed with. Makeiglob2 should get around this, but won't case-map things that aren't A-Za-z. A mix between them is possible that will work for both: change the m/^A-Za-z/ in makeiglob2 to m/<os-specifc path metachars>/. (os-specifc path metachars would be \ and : on win32, / on unix-likes, : on macos?) Most of the differences between these two, though, are in though-model. makeiglob is how I think. makeiglob2 is designed to be easy to follow for those newer to perl. Lists are happy things.

    sub makeiglob { return join "", map "[\U$_\L$_]", split //, $_[0]; } sub makeiglob2 { $out=""; foreach (split //, $_[0]) { if (m/[^A-Za-z]/) { $out .= $_; } else { $out .= "[" . uc($_) . lc($_) . "]"; } } } print glob(makeiglob(shift));


    Confession: It does an Immortal Body good.

      File::Glob has a case insensitive mode, so assuming you have two files, abc.pl and abc.PL the following will display them both.
      use File::Glob ':glob'; print "$_\n" for bsd_glob('*.pl', GLOB_NOCASE);
      However, NOCASE mode doesn't seem to be working properly if there are no wildcard characters in the glob:
      use File::Glob ':glob'; print "$_\n" for bsd_glob('abc.pl', GLOB_NOCASE);
      That should display both filenames but it only returns abc.pl for me. (tested using 5.6.1 and 5.8.0 on RH7.3)

      Is this a bug, or am I confused about how it should behave?

      -Blake

Re: Case insensitive file testing
by BUU (Prior) on Aug 07, 2002 at 06:07 UTC
    whats wrong with ls | grep -i ?, or in perl terms (/file/i and print) while <*>