if ($line =~ /^%(.{1,100})$/){ $name = $1; $name =~ s/\s//g; #this is the variable I think you want to remove spaces from. print "EEEEEEEEEEEEEEEEEEEEEEEEEEEE: $name\n"; } $outfile = "outfile['$name'].txt"; open (OUTFILE, "+>>$outfile");