in reply to Renaming files

You've not included the actual rename in there (which I suspect you're aware of) but the code won't work because you're match should be m/\s+/g - the \s matches whitespace rather than the /s you have. Also the s///g is slightly incorrect. A basic outline might look something like:

#!/usr/bin/perl my $file = '.'; opendir(DIR,$file); @files=readdir(DIR); close(DIR); for(@files) { if ( m/ /g) { my $oldfile = $_; s/ /_/g; rename $oldfile, $_; } print $_."\n"; }

Of course, you need to consider what happens if you have a conflict such as what would happen if you had 2 files called 'test file' & 'test_file' - how would you handle this?

Hey, if there's code up ^^ there ^^, don't blame me if it doesn't work.

But today you took me walking, Through a land that we have lost,
While our children sit at websites, With no access to the cost

Replies are listed 'Best First'.
Re: Re: Renaming files
by thor (Priest) on Oct 25, 2002 at 18:59 UTC
    Of course, you need to consider what happens if you have a conflict such as what would happen if you had 2 files called 'test file' & 'test_file' - how would you handle this?
    If it were me, I would build a hash of arrays, the key of the hash being the new file name, and the array elements being all files that would have that new name. Here's a quicky:
    #!perl -w use strict; opendir(DIR,".") or die "Couldn't opendir on .: $!"; while($file = readdir(DIR)){ my $oldfile = $file; $file =~ s/\s+/_/g; push @{$hash{$file}}, $oldfile; } closedir(DIR) or warn "Couldn't close directory .: $!"; foreach my $key (keys %hash){ if(scalar(@{$hash{$key}}) != 1){ print "The following files would have been renamed to the same + thing:\n" local $"="\n"; print "@{$hash{$key}}", "\n"; } else{ print "$hash{$key}[0] -> $key " my $status = rename $hash{$key}[0], $key; if(!$status){ print "Failed\n"; } else{ print "Succeeded\n"; } } }

    thor

Re: Re: Renaming files
by Anonymous Monk on Oct 25, 2002 at 17:12 UTC
    Thank you!