http://www.perlmonks.org?node_id=118263

shadox has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, i will explain my problem the best i can: Lets say i am reading data from a filehandle or from a server using sockets, then:

my $line = <FILE>; print "$line \n";

Will read a line from the file ( in this case ) and print it ( i asume that the file opened ok , and it contain data)

If the line was something like "\tHi\n\tthere!!", then when use print i will get something like:

Hi there!!

But i want to get "\tHi\n\tthere!!"
In this case i know that the backslashed characters are \n and \t, so i can just replace all the \t for \\t and \n to \\n, so when i print $line i will see them then,
My question is, if i don't know what is inside $line, how can i print it so i can see all the backslashed characters?


Dreams they just disapear into the shadows,
then they become true....

Replies are listed 'Best First'.
Re: Looking for backslashed characters
by thatguy (Parson) on Oct 11, 2001 at 20:46 UTC
    String::Escape seems to do what you ask.

    print printable( "\tNow is the time\nfor all good folks\n" ); \tNow is the time\nfor all good folks\n

    tested code:

    #!/usr/bin/perl -w use String::Escape qw( printable ) ; open(FILE," text.txt"); while(<FILE>){ print printable($_); } close(FILE);

    -p
Re: Looking for backslashed characters
by broquaint (Abbot) on Oct 11, 2001 at 20:49 UTC
    The problem is that those characters aren't literally back-slashed! What happens is that the backslash escapes the letter after it to become an escape character, so you're actually after these special escape characters. Something like this might be what you're after -
    %ctrl_chars = ("\n" => '\n', "\t" => '\t', "\r" => '\r'); $line =~ s/$_/$ctrl_chars{$_}/ for (keys %ctrl_chars);
    Of course you may want to replace other escape characters, in which case you'll probably want to check you the ascii table (see. man ascii(7).
    HTH

    broquaint