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

Hi I have several tab delimited files and I wanted to make sure that the entries in these files were actually tab delimited, By printing in some way the escape characters for example: Name Address (would become) Name\tAddress\t (this) I would also be interested in printing \s and \n etc... Cheers!

Replies are listed 'Best First'.
Re: printing escape characters
by sauoq (Abbot) on Nov 10, 2005 at 21:36 UTC

    Minimally: s/\t/\\t/g;

    Something more complete:

    my %ws = ( "\x09" => qw( \t ), "\x0A" => qw( \n ), "\x0C" => qw( \f ), "\x0D" => qw( \r ), "\x20" => qw( \s ), ); while (<>) { s/(\s)/$ws{$1}/g; print; print "\n"; # keep it line for line. }

    Note that printing "\s" for a space is pretty contrived... "\s" really only makes sense in the context of a regular expression. It isn't a real escape for a space.

    Something like this would be more general...

    perl -pe 's/(\s)/sprintf"\\x%02x",ord$1/ge;$_.=$/'

    Update: Added \f and more general one-liner.

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: printing escape characters
by GrandFather (Saint) on Nov 10, 2005 at 21:47 UTC
    use strict; use warnings; my $str = "\tthis is a sample string\nwith various white space charact +ers\n"; my $str2 = $str; $str2 =~ tr/\t \n/\0\1\2/; $str2 =~ s/([\0\1\2])/('\t', '\s', "\\n\n")[ord($1)]/ge; print $str."\n"; print $str2;

    Prints:

    this is a sample string with various white space characters \tthis\sis\sa\ssample\sstring\n with\svarious\swhite\sspace\scharacters\n

    Update: line breaks per sauoq


    Perl is Huffman encoded by design.
Re: printing escape characters
by ikegami (Patriarch) on Nov 10, 2005 at 22:00 UTC

    There are many non-Perl solutions to this problems. For example, you could use od in unix. Also, many text editors (including UltraEdit and Word in Windows) have the option of displaying whitespace.