use strict; my $Kine = "Hello, FLF12. Would you like to play FLF22?"; # I've substituted array refs for the SQL query. It's # approximately the same as the 'while' line you have. foreach my $row (["Dr. Falken", "a game"], ["Bobby Fischer", "some chess"]) { my @Replacement = (); $Replacement[12]=$row->[0]; $Replacement[22]=$row->[1]; $Kine=~s/FLF(\d\d)/$Replacement[$1]/ge; print $Kine, "\n"; }