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

Why wouldn't my renaming a file work when I loop through my array?
foreach my $x (@files) { print $x->{filename} . "\t" . localtime($x->{mtime}) . "\t" . $x-> +{size} . "\n"; rename $x->{filename}, "TEST" . $ext; ++$ext; }

Replies are listed 'Best First'.
Re: Rename not working
by Corion (Patriarch) on Jul 21, 2008 at 19:13 UTC

    Instead of asking us, why not ask Perl?

    my $target = "TEST" . $ext; rename $x->{filename}, $target or die "Couldn't rename '$x->{filename}' to '$target': $!";
      That was helpful, I didn't relize I was able to put that addidional line in there. Shouldn't the rename automatically know that's the directory I want to rename the file in. Any suggestions on how to do that? Dave
        If either argument doesn't specify a directory, the current directory is assumed.
        use File::Spec::Functions qw( catfile ); use File::Basename qw( dirname ); my $src_qn = $x->{filename}; my $dir_qn = dirname($src_qn); my $dst_fn = "TEST$ext"; my $dst_qn = catfile($dir_qn, $dst_fn); rename($src_qn, $dst_qn) or die("...: $!\n");

        My naming convention:
        fn = unqualified file name
        qn = qualified file name (i.e. rel or abs path)
        fqn = fully qualified file name (i.e. abs path)
        And only pass qn/fqn to system functions.

        Some of the lines can be combined, but I wanted to be explicit for clarity and demonstration purposes.

        Your operating system wants you to be more explicit than your shell wants you to be. You will need to construct the target name then from the directory and the filename:

        use File::Spec; my $target_dir = 'TEST'; my $source = 'foo.txt'; my $target = File::Spec->catfile($target_dir, $source); rename $source => $target or die "Couldn't rename '$source' to '$target': $!";