sowais has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks! I am trying to change the file extension of all files with .txt to .html. I am using windows. Here is what I have so far. It runs fine without errors but doesnt provide the expected result. Could you please help? Thanks!

#!/usr/local/bin/perl use strict; use warnings; use File::Copy; my $directory = 'C:\Perl'; chdir($directory) or die "Can't chdir to $directory $!"; opendir(DIR, $directory) || die "Couldn't opendir: $!\n"; my @filesWithSpaces = grep(/.*\s.*\..*/, readdir (DIR)); foreach (@filesWithSpaces) { my $newName = $_; $newName =~ s/html$/txt/g; print "RENAMING: $_ -> $newName \n"; rename($_, $newName); } closedir(DIR);

Sorry I did some more troubleshooting and got it working. Thank you!

#!/usr/local/bin/perl use strict; use warnings; use File::Copy; my $directory = 'C:\Perl'; chdir($directory) or die "Can't chdir to $directory $!"; opendir(DIR, $directory) || die "Couldn't opendir: $!\n"; my @files = grep { $_ ne '.' && $_ ne '..' } readdir DIR; foreach(@files) { print $_,"\n"; my $newName = $_; $newName =~ s/html$/txt/g; print "RENAMING: $_ -> $newName \n"; rename($_, $newName); } closedir(DIR);

Replies are listed 'Best First'.
Re: Changing file extensions
by wind (Priest) on May 05, 2011 at 23:14 UTC
    You're regex appears to be inverted if you want to change .txt to .html. Also, a global modifier is not necessary.
    $newName =~ s/html$/txt/g;
    The following would probably get you what you want:
    use strict; use warnings; my $directory = 'C:\Perl'; chdir($directory) or die "Can't chdir to $directory $!"; opendir my $dh, $directory or die "Couldn't opendir: $!\n"; foreach (readdir $dh) { next if /^\.+$/; if ((my $html = $_) =~ s/txt$/html/) { rename($_, $html) or die "Can't rename: $!"; } } closedir $dh;
Re: Changing file extensions
by BrowserUk (Patriarch) on May 05, 2011 at 23:57 UTC

    Why not:

    system 'ren *.txt *.html';

    Or just type it on the command line.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Changing file extensions
by tchrist (Pilgrim) on May 05, 2011 at 23:33 UTC
      Speaking of shell command, it's way simpler than that:
      >rename *.txt *.html
      aka
      >ren *.txt *.html
Re: Changing file extensions
by John M. Dlugosz (Monsignor) on May 06, 2011 at 07:24 UTC
    Wouldn't it be simpler just to use the shell? rename *.txt *.html.