P
Paul Lalli
A coworker just presented me with this task. I came up with two
solutions, but I don't like either of them. He has a text document
and wants to scan it for characters such as newline, tab, form feed,
carriage return, vertical tab. If found, he wants to replace them
with their typical representation (ie, \n, \t, \f, \r, \v).
I first gave him the obvious:
$string =~ s/\n/\\n/;
$string =~ s/\t/\\t/;
$string =~ s/\f/\\f/;
$string =~ s/\r/\\r/;
$string =~ s/\v/\\v/;
which I don't like because of how much copy/paste is involved. Then I
came up with:
for (qw/n t f r v/) {
my $meta = eval("\\$_");
$string =~ s/$meta/\\$_/;
}
which I don't like, because the comment he'd have to put in the code
to explain it would be longer than the code itself, or the first
version.
So can anyone think of a better way? Is there any kind of intrinsic
link between a newline character and the letter 'n' that could be used
to go "backwards" here?
Thanks,
Paul Lalli
solutions, but I don't like either of them. He has a text document
and wants to scan it for characters such as newline, tab, form feed,
carriage return, vertical tab. If found, he wants to replace them
with their typical representation (ie, \n, \t, \f, \r, \v).
I first gave him the obvious:
$string =~ s/\n/\\n/;
$string =~ s/\t/\\t/;
$string =~ s/\f/\\f/;
$string =~ s/\r/\\r/;
$string =~ s/\v/\\v/;
which I don't like because of how much copy/paste is involved. Then I
came up with:
for (qw/n t f r v/) {
my $meta = eval("\\$_");
$string =~ s/$meta/\\$_/;
}
which I don't like, because the comment he'd have to put in the code
to explain it would be longer than the code itself, or the first
version.
So can anyone think of a better way? Is there any kind of intrinsic
link between a newline character and the letter 'n' that could be used
to go "backwards" here?
Thanks,
Paul Lalli