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

I have a file consisting of a question on each line. I have created an array with the contents of this file. Some questions are having a \t or \n character.

my $filename_mh_sc_8_qnt = 'mh_science_8_qnt.txt'; open my $mh_sc_8_qnt, '<', $filename_mh_sc_8_qnt or die "Cannot open ' +$filename_mh_sc_8_qnt' for reading: $!"; my @Science = <$mh_sc_8_qnt>; my @shuffle = shuffle @Science; #shuffle the questions my $counter = 1; #number the question. foreach my $qnt (@shuffle){ print $counter, ". " . $qnt ."\n\n"; $counter++; }; print "\n";

The questions with \t and \n characters are not converting to tab and new line. example

Give reasons: \n\n\t(a) Grooves are made in tyres.\n\t(b) Gymnasts apply a coarse substance on their hands.

How can print function convert the \t \n in such case. Thanks

Replies are listed 'Best First'.
Re: print tab within an element of an array
by choroba (Cardinal) on Jan 24, 2018 at 12:21 UTC
    Just replace them:
    $qnt =~ s/\\t/\t/g; $qnt =~ s/\\n/\n/g;
    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      Thanks. Works like a charm

Re: print tab within an element of an array
by haukex (Archbishop) on Jan 24, 2018 at 12:26 UTC

    So do I understand correctly your input file contains literal backslashes followed by a letter, and not the control characters themselves?

    IMO the best way to do this is make the replacements yourself, e.g. $string =~ s/\\n/\n/g; $string =~ s/\\t/\t/g; (Update before posting: as choroba just showed too). There are of course other ways (trickery with eval, which should be considered unsafe, or CPAN modules), but if it's just those two characters, doing the replacement yourself is probably easiest. Note those regexes don't take into account multiple backslashes, that is, if your input contains \\n or \\\\n - you'd have to show us more sample input if that is the case.

      Thanks for your suggestion. Now it is working as expected.

Re: print tab within an element of an array
by haukex (Archbishop) on Jan 24, 2018 at 13:42 UTC

    Going a bit overkill, but the following supports a large subset of the escape sequences supported by Perl (Quote and Quote like Operators). Even though it uses eval (via s///ee) it's fairly safe as it only evaluates known escape sequences.

    $str =~ s{( \\ (?: [tnrfbae\\] | [xNo] \{ [-+,\w ]* \} | [0-7]{1,3} | x[0-9A-Fa-f]{0,2} | c[\@A-Za-z[\]^_?] ) )}{ qq{"$1"} }msxeeg;