Using debugger's x directive to pretty-print n

2019-08-05 02:01发布

问题:

[NOTE: this question is a spinoff of an earlier question of mine. At the time I posted that earlier question I did not realize that it actually asks about two different issues. Thanks to a comment by tripleee, I figured out the answer to one of the two. The question below limits itself to the remaining problem.]


I'll use the short demo script below to illustrate the problem.

# -*- coding: utf-8 -*-
use strict;
use feature 'unicode_strings';
use POSIX 'locale_h';
use locale;
use utf8;

setlocale( LC_CTYPE, 'de_DE.UTF-8' );
binmode( STDOUT, ':utf8' );

my $non_ascii = 'ßäöüÄÖÜ';
print "$non_ascii\n";

my @non_ascii = split //, $non_ascii;
print "$_\n" for @non_ascii;

$DB::single = 1; 1;  # return control to DB

(The last line is effectively a breakpoint.)

OK, now I run this under the Perl debugger:

% perl -d dbtest.pl

Loading DB routines from perl5db.pl version 1.37
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(dbtest.pl:8):            setlocale( LC_CTYPE, 'de_DE.UTF-8' );
  DB<1> c
ßäöüÄÖÜ
ß
ä
ö
ü
Ä
Ö
Ü
main::(dbtest.pl:17):           $DB::single = 1; 1;  # return control to DB
  DB<1> 

So far so good: the script produced the expected output, and now the debugger has entered into single-step mode, and is waiting for input.

At this point, print still produces the correct (i.e. human-readable) output:

  DB<1> print $non_ascii
ßäöüÄÖÜ
  DB<2> print "$_\n" for @non_ascii
ß
ä
ö
ü
Ä
Ö
Ü
  DB<3> 

But if I now use the x directive to pretty-print the contents of the @non_ascii array, the output is no longer looks right:

  DB<3> x \@non_ascii
0  ARRAY(0x7fab6196f790)
   0  '\337'
   1  '\344'
   2  '\366'
   3  '\374'
   4  '\304'
   5  '\326'
   6  '\334'
  DB<4> binmode( STDOUT, ':utf8' );
  DB<5> x \@non_ascii
0  ARRAY(0x7fab6196f790)
   0  '\337'
   1  '\344'
   2  '\366'
   3  '\374'
   4  '\304'
   5  '\326'
   6  '\334'
  DB<6> 

How can get x to produce human-readable output?

回答1:

OK, I figured it out. The solution is

  DB<10> binmode( $DB::OUT, ':utf8' )
  DB<11> x \@non_ascii
0  ARRAY(0x7fdae891e2a8)
   0  'ß'
   1  'ä'
   2  'ö'
   3  'ü'
   4  'Ä'
   5  'Ö'
   6  'Ü'
  DB<12>

One can put the binmode( $DB::OUT, ':utf8' ) setting in one's .perldb to make it persistent.