Cookie Notice

As far as I know, and as far as I remember, nothing in this page does anything with Cookies.

2009/10/09

Avoiding Wallop with Perl

This is a little bit of Perl code that copies a file, but if a file by that name exists, appends a number between the name and the suffix.



#!/usr/bin/perl
use Modern::Perl ;
use File::Copy ;

my $from = '/home/jacoby/test.test.pl' ;
my $to = '/home/jacoby/target.target.pl' ;

while ( -f $to ) {
my @to = split m{\.}mx , $to ;
my $suffix = pop @to ;
if ( scalar @to == 1 ) {
my $num = 1 ;
push @to , $num ;
push @to , $suffix ;
}
elsif ( $to[-1] !~ m{\D}mx ) {
my $num = pop @to ;
$num ++ ;
push @to , $num ;
push @to , $suffix ;
}
else {
my $num = 1 ;
push @to , $num ;
push @to , $suffix ;
}
$to = join '.' , @to ;
}
say "F\t" . $from ;
say "T\t" . $to ;
copy $from , $to ;