How to check file exists and rename to perl

Possible duplicate: Rename and move files in Bash or Perl

I am a curious newbie to Perl and looking for a script that will handle moving a file.

#!/usr/bin/perl -w
$filename = 'DUMBFILE';
$destination = '/some/location/';
if (-e $destination + $filename) {
  print "File Exists ! Renaming ..";
  move ('/tmp/' + $filename, $destination + $filename + '.1');
} else {
  move ('/tmp/' + $filename, $destination + $filename);
}

I can rename it to 1, but I want it to be renamed gradually, for example, if file 1 exists, rename it to .2 and .3 if .2 exists.

EDIT: and save the extension the same way; a similar .exe file becomes a .exe.1 file, a .exe.2 file, etc.

+3
source share
4 answers
#!/usr/bin/perl
use strict;
use warnings;

use File::Spec::Functions qw'catfile';
use File::Copy qw'move';
use autodie    qw'move';

my $filename    = 'DUMBFILE';
my $origin      = '/tmp';
my $destination = '/some/location';

my $path = catfile $destination, $filename;
{
  my $counter;
  while( -e $path ){
    $counter++;
    $path = catfile $destination, "$filename.$counter";
  }
}

move( catfile( $origin, $filename ), $path );
+3
source

You will need concatenation .instead +:

if (-e $destination . $filename) {

Or even better. You can use the module File::Spec:

use File::Spec;
...
if (-e File::Spec->join($destination, $filename)) {

And please, use strict;

File::Copy :

use File::Copy;
...
move($from, $to);
+4

, - :

use File::Copy;

sub construct_filename {
    my ($dir, $name, $counter) = @_;
    if ($name =~ /^(.*)\.(.*)$/) {
        return "$dir/$1.$counter.$2";
    } else {
        return "$dir/$name.$counter";
    }
}

if (-e "$destination$filename") {
    $counter = 1;
    while (-e construct_filename($destination,$filename,$counter)) {
        $counter++;
    }
    move("/tmp/$filename", construct_filename($destination,$filename,$counter));
} else {
    move("/tmp/$filename", "$destination$filename");
}

, perl ., +. , , . , .

, , , (, "$destination/$filename"). , File::Spec. , , , , , ; . File::Spec !

+4
#!/usr/bin/perl -w
$filename = 'DUMBFILE';
$destination = '/some/location/';
$filepath=$destination.$filename;
if (-e $filepath) {
  print "File Exists ! Renaming ..";
  $counter++;
  rename('/tmp/'.$filename.$filepath.$counter);
} else {
  move ('/tmp/'.$filename.$filepath);
}
+2
source

Source: https://habr.com/ru/post/1739312/


All Articles