in reply to How to replace spaces with different chars?

my @special_chars = qw( : ; , = - ); my $special_chars_glob_alt = "{".( join ",", map quotemeta, @special_chars )."}"; my $corrupt_qfn = ...; my $glob = $corrupt_qfn =~ s{ ( [ ] ) | ( [^\w ] ) }{ defined( $1 ) ? $special_chars_glob_alt : "\\$2" }xegr; my @possible_qfns = glob( $glob ); say for @possible_qfns;

or

use Algorithm::Loops qw( NestedLoops ); my @special_chars = qw( : ; , = - ); my $corrupt_qfn = ...; my $iter = NestedLoops([ map { $_ eq " " ? \@special_chars : [ $_ ] } split( /( )/, $corrupt_qfn, -1 ) ]); while ( my @parts = $iter->() ) { my $possible_qfn = join( "", @parts ); say for $possible_qfn; }

Four spaces results in 54 = 625 possible paths.

Replies are listed 'Best First'.
Re^2: How to replace spaces with different chars?
by AnomalousMonk (Archbishop) on Jul 07, 2022 at 02:43 UTC
    s{ ( [ ] ) | ( [^\w ] ) }{ defined( $1 ) ? $special_chars_re_class : "\\$2" }egr;

    I think this needs the /x modifier to work as advertised.


    Give a man a fish:  <%-{-{-{-<

      Oops, fixed.

Re^2: How to replace spaces with different chars?
by ikegami (Patriarch) on Jul 06, 2022 at 21:00 UTC

    The line at the bottom is hinting at the fact that this is not practical. What you could do instead of get a list of all the files, then use a regex match to find matching files.

    use File::Basename qw( fileparse basename ); my $special_chars_re_class = "[".( join "", map quotemeta, @special_chars )."]"; my ( $dir_qfn, $corrupt_fn ) = fileparse( $corrupt_qfn ); my $glob = quotemeta( $dir_qfn ) . '*'; my $re = $corrupt_fn =~ s{ ( [ ] ) | ( [^\w ] ) }{ defined( $1 ) ? $special_chars_re_class : "\\$2" }xegr; $re = qr/^\Q$dir_qfn\E$re\z/; while ( defined( my $qfn = glob( $glob ) ) ) { next if $qfn !~ $re; say $qfn; }

    As written, this assumes the spaces are just in the file name.

    This could easily be adapted to check for multiple files at once.

      I'm going to parrot Ikegami " this is not practical ".

      The real answer is to fix or replace the tool that gave you the incorrect output in the first place.

      -Scott

        Well, I was referring to doing 625 stat calls to check if a file exist. List a directory isn't impractical. Obviously, it would be better if the source could be fixed, but the solution in the post to which you replied is works fine.