If I ran perl script again,old logs should move with today date and new logs should generate.

Appreciate help for the below issue.
Im using below code.....I dont want to attach the logs when I ran the perl twice...I just want to take backup with today date and generate new logs...What I need to do for the below scirpt..............

1)if logs exist it should move the logs with extention of today date nad need to generate new one
2) only for first log file coming perfectly and for remaining logfiles and input.txt not adding in the outputfile.

Script :

my $last_name = '';
my $writeout;
 
while(<>) {
    if (/^#(\w+)#(.+)$/) {
        if ($last_name ne $1) {
            close $writeout if $writeout;
            open($writeout, '>>', "$1.log");
        }
        $last_name = $1;
if ($. == 1) {
print $writeout "Extract $1 \n";  
my $filename="input.txt";
open (my $ip, "<" , $filename) || die ("Can't open file input.txt");
while ( <$ip> ) {
    next if  (/^$/);
    print $writeout  "$_";
}
close $ip;
}
        print $writeout "$2\n" if $writeout;
    }
}
close $writeout or die;

Input files

more sanj.txt

#ext1#test1.tale2 drop
#ext1#test11.tale21 drop
#ext1#test123.tale21 drop
#ext2#test1.tale21 drop
#ext2#test12.tale21 drop
#ext3#test11.tale21 drop
#ext3#test123.tale21 drop
#ext4#test1.tale21 drop
#ext4#test124.tale21 drop
#ext1#test1.tale2 drop

more input.txt

1.1.1.1
2.2.2.2

logfile outputs

ls ext[0-9]*.log | while read f; do printf "file: $f\n--------------\n";cat $f; echo; done


file: ext1.log

  Extract ext1 
1.1.1.1
2.2.2.2
test1.tale2 drop
test11.tale21 drop
test123.tale21 drop
test1.tale2 drop

file: ext2.log
--------------
  test1.tale21 drop
test12.tale21 drop

file: ext3.log
--------------
 test11.tale21 drop
test123.tale21 drop

file: ext4.log
--------------
  test1.tale21 drop
test124.tale21 drop

I think you must detect if it's the first write to each logfile.
This is done with a hash (associative arrary).

...
while(<>) {
  if (/^#(\w+)#(.+)$/) {
    if ($last_name ne $1) {
      close $writeout if $writeout;
      if (!defined $fn{$1}) {
# not yet in hash => rename if present
        if (-f "$1.log") { rename "$1.log","$1.log.old"; }
# put in hash
        $fn{$1}="";
      }
      open($writeout, '>>', "$1.log");
    }
...

This renames to .old . Putting a date is left as an exercise.