I liked all of the comments in this thread. I would add a cautionary note about the use of $'.
In Perl versions <5.20 just this statement
my $afterstring = $'; can cause a huge regex performance penalty on every regex in the entire script, not just limited to where this variable is actually used.
https://perldoc.perl.org/perlvar.html gives the gory details. This thread shows a number of ways to avoid using this special variable and I recommend doing so. Perl versions can remain in use for a surprisingly long time because Perl is integral to the operation of many OS's and there will be a default "system Perl" that is only updated in a very conservative way. There are plenty of Perl 5.8 installations still out there. I don't see any compelling reason to use $' in this example and would not do so.