Reputation: 10467
I have a $string including special char following slash such as "1234\\n567\\t";
Note "\\n" and "\\t" are all two char, not three char. so when they are displayed, they are displayed as "\n" and "\t".
For some reason, I need to change the string as : "1234\n567`efg\t". How to do that in a simple way?
Here is my code, which I think can be improved:
@src_array = split(//, $string);
@des_array = ();
$size = $#src_array + 1;
$converting = 0;
for ($i = 0, $j = 0; $i< $size; $i++){
if ($converting == 1) {
# convert and replace '\\n' with '\n'
$des_array[$j++] = $slash_char{$src_array[$i]};
$converting = 0;
}
elsif ($src_array[$i] == '\\'){
$converting = 1;
}
else {
$des_array[$j++] = $src_array[$i];
}
}
my %slash_char = (
'a' => '\a',
'b' => '\b'
...
);
Upvotes: 0
Views: 320
Reputation: 62109
Well, the easy way is to use String::Escape:
use String::Escape 'unbackslash';
my $string = "1234\\n567\\t";
my $new_string = unbackslash($string);
Upvotes: 3
Reputation: 754090
Why not:
s/\\n/\n/g;
s/\\t/\t/g;
It would be nice to use tr///
, but that can't transform two characters to one.
Upvotes: 3