in reply to How can I use printf FORMAT strings for (Win32) shell globs?
G'day ozboomer,
"... but it appears pretty long-winded and ugly to me ..."
Agreed. I think you've thrown far too much code into that solution. In your first regex, you have character classes inside character classes ([\w]); and a pointless 'i' modifier (aim to avoid that anyway as it slows down the regex). You seem to have gone somewhat overboard with sprintf usage to create a regex; qr// would have been a better choice in my opinion (I've used it in the code below).
Here's the guts of what I think you need:
my @parts = $ARGV[0] =~ /^(\w+)%(\d+)d[.](\w+)$/; $parts[1] =~ s/^0*//; my $re = qr{(?x: ^ $parts[0] \d{$parts[1]} [.] $parts[2] $ )}; my $glob_str = "$parts[0]*.$parts[2]"; print for grep { /$re/ } glob $glob_str;
It would have been useful if you'd put together sample data, test input and actual/expected output. I dummied up these filenames for testing:
$ ls -1 Img* Img.png Img.svg Img0000.png Img1.png Img12.png Img123.png Img1234.png Img12345.png Img1239.png
I put those five lines of code into a script (pm_1195222_fmt_glob_re.pl) so that you can see each stage (much as your OP code does).
#!/usr/bin/perl -l use strict; use warnings; print 'Command line arg:'; print $ARGV[0]; my @parts = $ARGV[0] =~ /^(\w+)%(\d+)d[.](\w+)$/; print "Parts: @parts"; $parts[1] =~ s/^0*//; print "Parts (after stripping zeros): @parts"; my $re = qr{(?x: ^ $parts[0] \d{$parts[1]} [.] $parts[2] $ )}; print "Filter RE: $re"; my $glob_str = "$parts[0]*.$parts[2]"; print "Glob string: $glob_str"; print 'Found files:'; print for grep { /$re/ } glob $glob_str;
Here's a couple of sample runs (the first using your "Img%04d.png" string).
$ pm_1195222_fmt_glob_re.pl 'Img%04d.png' Command line arg: Img%04d.png Parts: Img 04 png Parts (after stripping zeros): Img 4 png Filter RE: (?^:(?x: ^ Img \d{4} [.] png $ )) Glob string: Img*.png Found files: Img0000.png Img1234.png Img1239.png
$ pm_1195222_fmt_glob_re.pl 'Img%03d.png' Command line arg: Img%03d.png Parts: Img 03 png Parts (after stripping zeros): Img 3 png Filter RE: (?^:(?x: ^ Img \d{3} [.] png $ )) Glob string: Img*.png Found files: Img123.png
You might also be interested in Win32::Autoglob.
— Ken
|
|---|