Re: 'safe' printing to the terminal

[email protected] (Michael Conrad) Wed, 13 May 2026 10:27:40 -0400
Newsgroups perl.perl5.porters
Message-ID <[email protected]>
On 5/12/26 10:02 AM, Michiel Beijen wrote:
> Hi Ruud,
>
> On Monday, May 11th, 2026 at 18:20, "Ruud H.G. van Tol" via perl5-porters <[email protected]> wrote:
>
>> On 2026-05-11 17:34, Michiel Beijen wrote:
>>   > On Monday, May 11th, 2026 at 12:29, "Ruud H.G. van Tol" via
>> perl5-porters <[email protected]> wrote:
>>   >
>>   >> printf has %q:
>>   >>
>>   >>    $  printf -v var "%q" "^[[4mtest^[[m"
>>   >>    $  echo $var
>>   >>    $  eval "echo $var"
>>   >
>>   > Yeah, that does what I want, but unfortunately this is not available
>> in _perl_ printf, only in _bash_ printf.
>>   >
>>   > Still looking for advise on how to print 'untrusted' input to a TTY
>> in a way that is sane!
>>
>> This was about the shell's printf, not about Perl's printf.
>>
>> What stops you from using it?
> Well, I can't assume that all users of File::MimeInfo have bash installed; moreover I would think perl should have a solution for this of its own. I'm partially inclined to see if I can make a CPAN module that implements printf with %q ;-)

%q seems to be the right idea.  But also, you said quotearg is many 
lines of C, but is it that bad when translated to perl?  I would guess 
it could probably be a two-liner.  Seems like all you need to do is 
replace characters with escapes and then wrap it in "\$'$_'" if any were 
replaced.

> Also, I think maybe I'd have a go to create something that you could use as an IO layer?

I don't think this would solve your problem.  In the "filename 
vulnerability" scenario, newline (\n) is one of the characters you need 
to guard against, because considering the lines of output as "records", 
embedding a \n in one record to make it look like two records is one of 
the vulnerabilities you need to solve.  An IO layer that escapes \n 
doesn't seem particularly useful.