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

Hi, I'm having this problem: I'm trying to input a character that will be used to separate fields for an output to a file. Example: if I input | the result string in the file will be: Field1|field2| etc... But how can I insert a special character like \t? I'm only getting: Field1\tField2\t etc... instead of the fields be separated by tabs. Is there a way to solve this? Regards, Kepler

Replies are listed 'Best First'.
Re: input special characters
by AppleFritter (Vicar) on Jul 13, 2014 at 10:26 UTC
      Hi, The input is $char = <>: Then I use it like this: $out = "Field1$charField2$char....." Regards, Kepler

        I'm not sure what the issue is, then. Take this snippet of code:

        chomp(my $sep = <>); say join $sep, @data;

        if I run this (with the above @data) and input a tab character, I do indeed get the output separated by tabs. Or do you want to be able to input the characters "\t" and have them interpreted as a tab, rather than a literal backslash followed by a literal lower-case t? In that case, you can use a regular expression to transform your separator:

        chomp(my $sep = <>); $sep =~ s/\\t/\t/g; say join $sep, @data;
Re: input special characters
by Anonymous Monk on Jul 13, 2014 at 11:32 UTC
    Well, the simplest solution is to provide a literal tab character (rather than two characters: backslash and t). Alternatively, you can try to make a tab out of backslash-t with eval.
    use strict; use warnings; my $t = '\\t'; print "$t:\n"; my $evaled = eval "qq/$t/"; print "$evaled:\n"
    Result:
    \t: :

    (perlmonks changes literal tab to several spaces, heh)

    Than again, maybe eval is more trouble than it's worth. I'd say a hash with all separators that you want to use would work better:
    my %seps = ( '\\t' => "\t", '\\n' => "\n", # etc ); my $input = <>; my $separator = $seps{$input};
      That works great... :) I was trying to substitute the "\" because of the \xhh character with hex. code hh. It's not working. Thanks. Kepler.
        If you decided to use eval, you should really consider this:
        # file eval.pl use strict; use warnings; my $sep = shift @ARGV; my $evaled = eval "qq/$sep/"; print "$evaled:\n"
        Now the user enters this:
        perl eval.pl 'hehe/; print "Hello there!\n"; unlink "./eval.pl"; q/foo +'
        Result:
        Useless use of a constant ("hehe") in void context at (eval 1) line 1. Hello there! foo:
        And the eval.pl file is gone. So, yeah... as I said, eval is usually more trouble than it's worth. Maybe consider module Safe, which provides restricted eval, if you're dealing with users there (users are evil).