in reply to sed to perl conversion

Try

perl -wne 'BEGIN {$b= "";} if (/\47[1-4]\47/) {$b= $_.$b;} elsif (/\47 +[5]\47/) {print $b, $_; $b= "";} else {print;}'

I'm not sure if it does what you want.