new_perl
new_perl

Reputation: 7735

Moving a file to another directory in Perl?

rename $ARGV[0], $ARGV[1] or warn "rename fails: $!\n";

When I run ./programe file.txt dir/ it always fails.

What's wrong here?

Upvotes: 2

Views: 2246

Answers (3)

ysth
ysth

Reputation: 98388

rename is expecting a full target path, not just a directory. Try:

./progname file.txt dir/file.txt

It would be nice if you would tell what error it failed with...

Upvotes: 5

MarcoS
MarcoS

Reputation: 13564

rename changes the name of a file, which is not what you're trying to do. You probably want to use the move function from File::Copy

Upvotes: 4

Quentin
Quentin

Reputation: 943098

From the perldoc for rename:

Behavior of this function varies wildly depending on your system implementation. For example, it will usually not work across file system boundaries, even though the system mv command sometimes compensates for this. Other restrictions include whether it works on directories, open files, or pre- existing files. Check perlport and either the rename(2) manpage or equivalent system documentation for details.

For a platform independent "move" function look at the File::Copy module.

So use File::Copy::move instead.

Upvotes: 7

Related Questions