G
Gary sCHENK
I am a self-taught at Perl. I use Perl a few times a year, mostly to
process text files. I'm trying to rename files in a directory. My
skills are quite rudimentary.
The files are currently named like this: SR-01-234-5.jpg
I want to rename them like this: SR-01-234-0005.jpg
I have a couple of thousand of these. I've already written several
several variations of the following script to get them to this stage,
but adding the extra zeros has me stumped. This is the script:
===============================================================================
#!perl -w
opendir( DH, "d:\\temp" ) or die "couldn't open d:\\temp: $! ";
while ( defined ( my $filename = readdir( DH ) ) ) {
my $foo = $filename;
if ($foo =~ /(^SR-\d{2}-\d{3}-)(\d+)([a-zA-Z]{0,1}\.jpg$)/ ) {
if ( length( $2 ) == 1 ) {
$foo =~ s/$1$2$3/$1000$2$3/;
rename( $filename, $foo );
#print "$1\n";
}
}
}
closedir( DH );
===============================================================================
The print statement is an attempt at debugging. When I comment out the
substitution and the call to rename and just print $1, the output is
what I expect. When I run this script as shown above, however, files
come up missing, or the zeros are added in the wrong place.
Is it possible to use match variables in substitutions? The llama book
shows match variables being used outside of regular expression
operations, but not in this fashion.
And why are the files being deleted? I'm really stumped, and would
appreciate any and all help.
All the best,
Gary Schenk
process text files. I'm trying to rename files in a directory. My
skills are quite rudimentary.
The files are currently named like this: SR-01-234-5.jpg
I want to rename them like this: SR-01-234-0005.jpg
I have a couple of thousand of these. I've already written several
several variations of the following script to get them to this stage,
but adding the extra zeros has me stumped. This is the script:
===============================================================================
#!perl -w
opendir( DH, "d:\\temp" ) or die "couldn't open d:\\temp: $! ";
while ( defined ( my $filename = readdir( DH ) ) ) {
my $foo = $filename;
if ($foo =~ /(^SR-\d{2}-\d{3}-)(\d+)([a-zA-Z]{0,1}\.jpg$)/ ) {
if ( length( $2 ) == 1 ) {
$foo =~ s/$1$2$3/$1000$2$3/;
rename( $filename, $foo );
#print "$1\n";
}
}
}
closedir( DH );
===============================================================================
The print statement is an attempt at debugging. When I comment out the
substitution and the call to rename and just print $1, the output is
what I expect. When I run this script as shown above, however, files
come up missing, or the zeros are added in the wrong place.
Is it possible to use match variables in substitutions? The llama book
shows match variables being used outside of regular expression
operations, but not in this fashion.
And why are the files being deleted? I'm really stumped, and would
appreciate any and all help.
All the best,
Gary Schenk