Elaborating on from Marshall's comment, it looks like you found some code in a dumpster, dusted it off, shuffled the lines a little and expected it to perform some, largely unspecified, task. Maybe this is because you have stripped out code you didn't think relevant before you showed it to us? In any case, as suggested by hv, a SSCCE would help a lot.
Your code as presented doesn't do as you claim. The rename line in the loop doesn't get hit because the loop body is not executed. In fact the spurious } at the end of the rename line means the code doesn't even compile. Maybe something closer to your intent is:
use strict;
use warnings;
use File::Basename;
use File::Spec;
my $attach = "file.png";
my $filename = File::Basename::fileparse($attach);
my $tempfile = File::Spec->catfile("tempdir", $filename);
my $new_filepath = File::Spec->catfile("tempdir", "allfiles.png");
rename $tempfile, $new_filepath
or die "Cannot rename file $tempfile to $new_filepath: $!";
Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond