The key is in the regex $name =~ s/_ref\d+$//;
This just deletes things at the end of string, like _ref3. If something like that is not there, then nothing happens! As general "rule of thumb", do not create special cases like "for the first file, we do X" otherwise we do "Y" unless needed. Add some print statements in the code to see what it is doing. Run the code with different orders of files (should give same result). Perl Regex "regular expressions" are an integral part of the language and you should master the use of \s\d\w and \S\D\W. You will go very far with them! Especially when used with the "anchors" of ^ and $ which say to start at beginning of var to be tested or back up from the end of var to be tested.
s/_ref\d+$//; means that we start at the end (the $ symbol means that), back up and see if something like _ref followed by one or more digits exists, _ref3, _ref34, etc. If it does, then it is deleted. \d means exactly one digit, \d+ means one or more digits in a row, \d* means maybe some digit or not (zero or one). The capital version \D means "not a digit", anything except 0-9. That's not used here, but that is what it would mean. | [reply] [d/l] [select] |