use warnings; use strict; open my $fh, '+>', 'output.txt' or die("Can't open the damn file!: $!"); while(my $line = 'mytextfile'); { chomp $line; my ($name, $num) = split(/\s+(?=\d)/, $line) # some lines have whitespace after the num $num =~ s/\s+//g; if ($num =~ /^\d{4}$/){ $num = "(333)-447-$num"; } elsif ($num =~ /^\d{3}-\d{4}$/){ $num = "(333)-$num"; } print $fh "$name $num\n"; }