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

I am having problems renaming files in a directory. I want to rename files for instance c:\folder\files\tree.txt to only 'tree'. Here is a snippet of what I'm working with. Help, please. use strict; my $dir = 'C:\duty\tasks\checks'; my @file = glob "$dir/file*9*"; my $word; foreach $word(@file) { print "One of the files is $word\n"; }

Replies are listed 'Best First'.
Re: Renaming file without forward slash
by dirving (Friar) on Feb 25, 2008 at 05:03 UTC

    You can use the standard module File::Basename to break a file apart into its path, filename, and extension.

    -- David Irving
Re: Renaming file without forward slash
by pc88mxer (Vicar) on Feb 25, 2008 at 03:43 UTC
    This will chop off the .txt extension on all the files in @file:

    ... foreach $word (@file) { if ((my $new = $word) =~ s/\.txt$//) { rename($word, $new) or die "unable to rename $word to $new: $!\n"; } }
    Is this what you're looking for?
      When I run it it takes away the .txt extension but I'm trying to also take out the rest of the path to the file and only have the filename
Re: Renaming file without forward slash
by hipowls (Curate) on Feb 25, 2008 at 08:45 UTC

    You have to double up the '\'s as they are escape characters even in single quote strings. So write 'C:\\duty\\tasks\\checks'. Also have a look at using File::Spec and File::Basename (to pinch dirving's good suggestion;)

Re: Renaming file without forward slash
by nikhil.patil (Sexton) on Feb 25, 2008 at 09:31 UTC
    Hi,
    You can use the following RegEx:
    $word =~ /(.*\\)*(.+)\..*/; print "One of the files is " . $2 . "\n";