I have just started to learn Perl, but I had a task come up that couldn't wait for my slow progress through Programming Perl, 3rd ed. This script renames files in a specified directory. It seems to work OK, but I am wondering if it could be better. By better, I mean more robust against user error, better form, with readability and maintainability being priorities. Also, I am wondering if my approach is being warped by my years of Microsoft-based development. In other words, is this thing Perlesque? The script is posted below.
Thanks in advance, -- Barry C. Hawkins Systems Consultant All Things Computed 404-795-9147 voice/fax http://www.allthingscomputed.com
#!/usr/bin/perl -w
# Filename: rename_files.pl # # Create Date: 07/10/2003 # # Author: Barry C. Hawkins # # Description: The purpose of this script is to # rename several hundred files with hard-coded # version number suffixes using a regular expression # substitution operation. The suffix convention # is -[major]-[minor], i.e. -1-0, and immediately # precedes the filename extension.
use strict;
# Prompt user for input print "Please enter the directory containing the files to be renamed.\n" . "(NOTE: Use forward slashes even on Windows, i.e. C:/temp): ";
# Remove trailing newline chomp(my $working_dir = <STDIN>);
# Open the specified directory opendir(DIR, $working_dir) or die "Could not open DIR; $!\n";
# Read the directory contents into an array # grep is being used to omit the . and .. entries my @files = grep{ not /^\.{1,2}\z/ } readdir DIR;
# Iterate through the array, processing each filename. foreach(@files) { # Generate the new filename string (my $new_name = $_) =~ s/-[0-9]-[0-9]//; # Print a line showing the new and old filenames print "$_\t $new_name\n"; # Rename the current file rename $working_dir . "/" . $_, $working_dir . "/" . $new_name or die "Could not rename $working_dir/" . "$_: $!"; }
# Release the filehandle close DIR;
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]