Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1280 lines
38 KiB

  1. #
  2. # Data/Dumper.pm
  3. #
  4. # convert perl data structures into perl syntax suitable for both printing
  5. # and eval
  6. #
  7. # Documentation at the __END__
  8. #
  9. package Data::Dumper;
  10. $VERSION = '2.121_12';
  11. #$| = 1;
  12. use 5.006_001;
  13. require Exporter;
  14. require overload;
  15. use Carp;
  16. BEGIN {
  17. @ISA = qw(Exporter);
  18. @EXPORT = qw(Dumper);
  19. @EXPORT_OK = qw(DumperX);
  20. # if run under miniperl, or otherwise lacking dynamic loading,
  21. # XSLoader should be attempted to load, or the pure perl flag
  22. # toggled on load failure.
  23. eval {
  24. require XSLoader;
  25. };
  26. $Useperl = 1 if $@;
  27. }
  28. XSLoader::load( 'Data::Dumper' ) unless $Useperl;
  29. # module vars and their defaults
  30. $Indent = 2 unless defined $Indent;
  31. $Purity = 0 unless defined $Purity;
  32. $Pad = "" unless defined $Pad;
  33. $Varname = "VAR" unless defined $Varname;
  34. $Useqq = 0 unless defined $Useqq;
  35. $Terse = 0 unless defined $Terse;
  36. $Freezer = "" unless defined $Freezer;
  37. $Toaster = "" unless defined $Toaster;
  38. $Deepcopy = 0 unless defined $Deepcopy;
  39. $Quotekeys = 1 unless defined $Quotekeys;
  40. $Bless = "bless" unless defined $Bless;
  41. #$Expdepth = 0 unless defined $Expdepth;
  42. $Maxdepth = 0 unless defined $Maxdepth;
  43. $Pair = ' => ' unless defined $Pair;
  44. $Useperl = 0 unless defined $Useperl;
  45. $Sortkeys = 0 unless defined $Sortkeys;
  46. $Deparse = 0 unless defined $Deparse;
  47. #
  48. # expects an arrayref of values to be dumped.
  49. # can optionally pass an arrayref of names for the values.
  50. # names must have leading $ sign stripped. begin the name with *
  51. # to cause output of arrays and hashes rather than refs.
  52. #
  53. sub new {
  54. my($c, $v, $n) = @_;
  55. croak "Usage: PACKAGE->new(ARRAYREF, [ARRAYREF])"
  56. unless (defined($v) && (ref($v) eq 'ARRAY'));
  57. $n = [] unless (defined($n) && (ref($v) eq 'ARRAY'));
  58. my($s) = {
  59. level => 0, # current recursive depth
  60. indent => $Indent, # various styles of indenting
  61. pad => $Pad, # all lines prefixed by this string
  62. xpad => "", # padding-per-level
  63. apad => "", # added padding for hash keys n such
  64. sep => "", # list separator
  65. pair => $Pair, # hash key/value separator: defaults to ' => '
  66. seen => {}, # local (nested) refs (id => [name, val])
  67. todump => $v, # values to dump []
  68. names => $n, # optional names for values []
  69. varname => $Varname, # prefix to use for tagging nameless ones
  70. purity => $Purity, # degree to which output is evalable
  71. useqq => $Useqq, # use "" for strings (backslashitis ensues)
  72. terse => $Terse, # avoid name output (where feasible)
  73. freezer => $Freezer, # name of Freezer method for objects
  74. toaster => $Toaster, # name of method to revive objects
  75. deepcopy => $Deepcopy, # dont cross-ref, except to stop recursion
  76. quotekeys => $Quotekeys, # quote hash keys
  77. 'bless' => $Bless, # keyword to use for "bless"
  78. # expdepth => $Expdepth, # cutoff depth for explicit dumping
  79. maxdepth => $Maxdepth, # depth beyond which we give up
  80. useperl => $Useperl, # use the pure Perl implementation
  81. sortkeys => $Sortkeys, # flag or filter for sorting hash keys
  82. deparse => $Deparse, # use B::Deparse for coderefs
  83. };
  84. if ($Indent > 0) {
  85. $s->{xpad} = " ";
  86. $s->{sep} = "\n";
  87. }
  88. return bless($s, $c);
  89. }
  90. if ($] >= 5.006) {
  91. # Packed numeric addresses take less memory. Plus pack is faster than sprintf
  92. *init_refaddr_format = sub {};
  93. *format_refaddr = sub {
  94. require Scalar::Util;
  95. pack "J", Scalar::Util::refaddr(shift);
  96. };
  97. } else {
  98. *init_refaddr_format = sub {
  99. require Config;
  100. my $f = $Config::Config{uvxformat};
  101. $f =~ tr/"//d;
  102. our $refaddr_format = "0x%" . $f;
  103. };
  104. *format_refaddr = sub {
  105. require Scalar::Util;
  106. sprintf our $refaddr_format, Scalar::Util::refaddr(shift);
  107. }
  108. }
  109. #
  110. # add-to or query the table of already seen references
  111. #
  112. sub Seen {
  113. my($s, $g) = @_;
  114. if (defined($g) && (ref($g) eq 'HASH')) {
  115. init_refaddr_format();
  116. my($k, $v, $id);
  117. while (($k, $v) = each %$g) {
  118. if (defined $v and ref $v) {
  119. $id = format_refaddr($v);
  120. if ($k =~ /^[*](.*)$/) {
  121. $k = (ref $v eq 'ARRAY') ? ( "\\\@" . $1 ) :
  122. (ref $v eq 'HASH') ? ( "\\\%" . $1 ) :
  123. (ref $v eq 'CODE') ? ( "\\\&" . $1 ) :
  124. ( "\$" . $1 ) ;
  125. }
  126. elsif ($k !~ /^\$/) {
  127. $k = "\$" . $k;
  128. }
  129. $s->{seen}{$id} = [$k, $v];
  130. }
  131. else {
  132. carp "Only refs supported, ignoring non-ref item \$$k";
  133. }
  134. }
  135. return $s;
  136. }
  137. else {
  138. return map { @$_ } values %{$s->{seen}};
  139. }
  140. }
  141. #
  142. # set or query the values to be dumped
  143. #
  144. sub Values {
  145. my($s, $v) = @_;
  146. if (defined($v) && (ref($v) eq 'ARRAY')) {
  147. $s->{todump} = [@$v]; # make a copy
  148. return $s;
  149. }
  150. else {
  151. return @{$s->{todump}};
  152. }
  153. }
  154. #
  155. # set or query the names of the values to be dumped
  156. #
  157. sub Names {
  158. my($s, $n) = @_;
  159. if (defined($n) && (ref($n) eq 'ARRAY')) {
  160. $s->{names} = [@$n]; # make a copy
  161. return $s;
  162. }
  163. else {
  164. return @{$s->{names}};
  165. }
  166. }
  167. sub DESTROY {}
  168. sub Dump {
  169. return &Dumpxs
  170. unless $Data::Dumper::Useperl || (ref($_[0]) && $_[0]->{useperl}) ||
  171. $Data::Dumper::Useqq || (ref($_[0]) && $_[0]->{useqq}) ||
  172. $Data::Dumper::Deparse || (ref($_[0]) && $_[0]->{deparse});
  173. return &Dumpperl;
  174. }
  175. #
  176. # dump the refs in the current dumper object.
  177. # expects same args as new() if called via package name.
  178. #
  179. sub Dumpperl {
  180. my($s) = shift;
  181. my(@out, $val, $name);
  182. my($i) = 0;
  183. local(@post);
  184. init_refaddr_format();
  185. $s = $s->new(@_) unless ref $s;
  186. for $val (@{$s->{todump}}) {
  187. my $out = "";
  188. @post = ();
  189. $name = $s->{names}[$i++];
  190. if (defined $name) {
  191. if ($name =~ /^[*](.*)$/) {
  192. if (defined $val) {
  193. $name = (ref $val eq 'ARRAY') ? ( "\@" . $1 ) :
  194. (ref $val eq 'HASH') ? ( "\%" . $1 ) :
  195. (ref $val eq 'CODE') ? ( "\*" . $1 ) :
  196. ( "\$" . $1 ) ;
  197. }
  198. else {
  199. $name = "\$" . $1;
  200. }
  201. }
  202. elsif ($name !~ /^\$/) {
  203. $name = "\$" . $name;
  204. }
  205. }
  206. else {
  207. $name = "\$" . $s->{varname} . $i;
  208. }
  209. # Ensure hash iterator is reset
  210. if (ref($val) eq 'HASH') {
  211. keys(%$val);
  212. }
  213. my $valstr;
  214. {
  215. local($s->{apad}) = $s->{apad};
  216. $s->{apad} .= ' ' x (length($name) + 3) if $s->{indent} >= 2;
  217. $valstr = $s->_dump($val, $name);
  218. }
  219. $valstr = "$name = " . $valstr . ';' if @post or !$s->{terse};
  220. $out .= $s->{pad} . $valstr . $s->{sep};
  221. $out .= $s->{pad} . join(';' . $s->{sep} . $s->{pad}, @post)
  222. . ';' . $s->{sep} if @post;
  223. push @out, $out;
  224. }
  225. return wantarray ? @out : join('', @out);
  226. }
  227. #
  228. # twist, toil and turn;
  229. # and recurse, of course.
  230. # sometimes sordidly;
  231. # and curse if no recourse.
  232. #
  233. sub _dump {
  234. my($s, $val, $name) = @_;
  235. my($sname);
  236. my($out, $realpack, $realtype, $type, $ipad, $id, $blesspad);
  237. $type = ref $val;
  238. $out = "";
  239. if ($type) {
  240. # Call the freezer method if it's specified and the object has the
  241. # method. Trap errors and warn() instead of die()ing, like the XS
  242. # implementation.
  243. my $freezer = $s->{freezer};
  244. if ($freezer and UNIVERSAL::can($val, $freezer)) {
  245. eval { $val->$freezer() };
  246. warn "WARNING(Freezer method call failed): $@" if $@;
  247. }
  248. require Scalar::Util;
  249. $realpack = Scalar::Util::blessed($val);
  250. $realtype = $realpack ? Scalar::Util::reftype($val) : ref $val;
  251. $id = format_refaddr($val);
  252. # if it has a name, we need to either look it up, or keep a tab
  253. # on it so we know when we hit it later
  254. if (defined($name) and length($name)) {
  255. # keep a tab on it so that we dont fall into recursive pit
  256. if (exists $s->{seen}{$id}) {
  257. # if ($s->{expdepth} < $s->{level}) {
  258. if ($s->{purity} and $s->{level} > 0) {
  259. $out = ($realtype eq 'HASH') ? '{}' :
  260. ($realtype eq 'ARRAY') ? '[]' :
  261. 'do{my $o}' ;
  262. push @post, $name . " = " . $s->{seen}{$id}[0];
  263. }
  264. else {
  265. $out = $s->{seen}{$id}[0];
  266. if ($name =~ /^([\@\%])/) {
  267. my $start = $1;
  268. if ($out =~ /^\\$start/) {
  269. $out = substr($out, 1);
  270. }
  271. else {
  272. $out = $start . '{' . $out . '}';
  273. }
  274. }
  275. }
  276. return $out;
  277. # }
  278. }
  279. else {
  280. # store our name
  281. $s->{seen}{$id} = [ (($name =~ /^[@%]/) ? ('\\' . $name ) :
  282. ($realtype eq 'CODE' and
  283. $name =~ /^[*](.*)$/) ? ('\\&' . $1 ) :
  284. $name ),
  285. $val ];
  286. }
  287. }
  288. if ($realpack and $realpack eq 'Regexp') {
  289. $out = "$val";
  290. $out =~ s,/,\\/,g;
  291. return "qr/$out/";
  292. }
  293. # If purity is not set and maxdepth is set, then check depth:
  294. # if we have reached maximum depth, return the string
  295. # representation of the thing we are currently examining
  296. # at this depth (i.e., 'Foo=ARRAY(0xdeadbeef)').
  297. if (!$s->{purity}
  298. and $s->{maxdepth} > 0
  299. and $s->{level} >= $s->{maxdepth})
  300. {
  301. return qq['$val'];
  302. }
  303. # we have a blessed ref
  304. if ($realpack) {
  305. $out = $s->{'bless'} . '( ';
  306. $blesspad = $s->{apad};
  307. $s->{apad} .= ' ' if ($s->{indent} >= 2);
  308. }
  309. $s->{level}++;
  310. $ipad = $s->{xpad} x $s->{level};
  311. if ($realtype eq 'SCALAR' || $realtype eq 'REF') {
  312. if ($realpack) {
  313. $out .= 'do{\\(my $o = ' . $s->_dump($$val, "\${$name}") . ')}';
  314. }
  315. else {
  316. $out .= '\\' . $s->_dump($$val, "\${$name}");
  317. }
  318. }
  319. elsif ($realtype eq 'GLOB') {
  320. $out .= '\\' . $s->_dump($$val, "*{$name}");
  321. }
  322. elsif ($realtype eq 'ARRAY') {
  323. my($v, $pad, $mname);
  324. my($i) = 0;
  325. $out .= ($name =~ /^\@/) ? '(' : '[';
  326. $pad = $s->{sep} . $s->{pad} . $s->{apad};
  327. ($name =~ /^\@(.*)$/) ? ($mname = "\$" . $1) :
  328. # omit -> if $foo->[0]->{bar}, but not ${$foo->[0]}->{bar}
  329. ($name =~ /^\\?[\%\@\*\$][^{].*[]}]$/) ? ($mname = $name) :
  330. ($mname = $name . '->');
  331. $mname .= '->' if $mname =~ /^\*.+\{[A-Z]+\}$/;
  332. for $v (@$val) {
  333. $sname = $mname . '[' . $i . ']';
  334. $out .= $pad . $ipad . '#' . $i if $s->{indent} >= 3;
  335. $out .= $pad . $ipad . $s->_dump($v, $sname);
  336. $out .= "," if $i++ < $#$val;
  337. }
  338. $out .= $pad . ($s->{xpad} x ($s->{level} - 1)) if $i;
  339. $out .= ($name =~ /^\@/) ? ')' : ']';
  340. }
  341. elsif ($realtype eq 'HASH') {
  342. my($k, $v, $pad, $lpad, $mname, $pair);
  343. $out .= ($name =~ /^\%/) ? '(' : '{';
  344. $pad = $s->{sep} . $s->{pad} . $s->{apad};
  345. $lpad = $s->{apad};
  346. $pair = $s->{pair};
  347. ($name =~ /^\%(.*)$/) ? ($mname = "\$" . $1) :
  348. # omit -> if $foo->[0]->{bar}, but not ${$foo->[0]}->{bar}
  349. ($name =~ /^\\?[\%\@\*\$][^{].*[]}]$/) ? ($mname = $name) :
  350. ($mname = $name . '->');
  351. $mname .= '->' if $mname =~ /^\*.+\{[A-Z]+\}$/;
  352. my ($sortkeys, $keys, $key) = ("$s->{sortkeys}");
  353. if ($sortkeys) {
  354. if (ref($s->{sortkeys}) eq 'CODE') {
  355. $keys = $s->{sortkeys}($val);
  356. unless (ref($keys) eq 'ARRAY') {
  357. carp "Sortkeys subroutine did not return ARRAYREF";
  358. $keys = [];
  359. }
  360. }
  361. else {
  362. $keys = [ sort keys %$val ];
  363. }
  364. }
  365. while (($k, $v) = ! $sortkeys ? (each %$val) :
  366. @$keys ? ($key = shift(@$keys), $val->{$key}) :
  367. () )
  368. {
  369. my $nk = $s->_dump($k, "");
  370. $nk = $1 if !$s->{quotekeys} and $nk =~ /^[\"\']([A-Za-z_]\w*)[\"\']$/;
  371. $sname = $mname . '{' . $nk . '}';
  372. $out .= $pad . $ipad . $nk . $pair;
  373. # temporarily alter apad
  374. $s->{apad} .= (" " x (length($nk) + 4)) if $s->{indent} >= 2;
  375. $out .= $s->_dump($val->{$k}, $sname) . ",";
  376. $s->{apad} = $lpad if $s->{indent} >= 2;
  377. }
  378. if (substr($out, -1) eq ',') {
  379. chop $out;
  380. $out .= $pad . ($s->{xpad} x ($s->{level} - 1));
  381. }
  382. $out .= ($name =~ /^\%/) ? ')' : '}';
  383. }
  384. elsif ($realtype eq 'CODE') {
  385. if ($s->{deparse}) {
  386. require B::Deparse;
  387. my $sub = 'sub ' . (B::Deparse->new)->coderef2text($val);
  388. $pad = $s->{sep} . $s->{pad} . $s->{apad} . $s->{xpad} x ($s->{level} - 1);
  389. $sub =~ s/\n/$pad/gse;
  390. $out .= $sub;
  391. } else {
  392. $out .= 'sub { "DUMMY" }';
  393. carp "Encountered CODE ref, using dummy placeholder" if $s->{purity};
  394. }
  395. }
  396. else {
  397. croak "Can\'t handle $realtype type.";
  398. }
  399. if ($realpack) { # we have a blessed ref
  400. $out .= ', \'' . $realpack . '\'' . ' )';
  401. $out .= '->' . $s->{toaster} . '()' if $s->{toaster} ne '';
  402. $s->{apad} = $blesspad;
  403. }
  404. $s->{level}--;
  405. }
  406. else { # simple scalar
  407. my $ref = \$_[1];
  408. # first, catalog the scalar
  409. if ($name ne '') {
  410. $id = format_refaddr($ref);
  411. if (exists $s->{seen}{$id}) {
  412. if ($s->{seen}{$id}[2]) {
  413. $out = $s->{seen}{$id}[0];
  414. #warn "[<$out]\n";
  415. return "\${$out}";
  416. }
  417. }
  418. else {
  419. #warn "[>\\$name]\n";
  420. $s->{seen}{$id} = ["\\$name", $ref];
  421. }
  422. }
  423. if (ref($ref) eq 'GLOB' or "$ref" =~ /=GLOB\([^()]+\)$/) { # glob
  424. my $name = substr($val, 1);
  425. if ($name =~ /^[A-Za-z_][\w:]*$/) {
  426. $name =~ s/^main::/::/;
  427. $sname = $name;
  428. }
  429. else {
  430. $sname = $s->_dump($name, "");
  431. $sname = '{' . $sname . '}';
  432. }
  433. if ($s->{purity}) {
  434. my $k;
  435. local ($s->{level}) = 0;
  436. for $k (qw(SCALAR ARRAY HASH)) {
  437. my $gval = *$val{$k};
  438. next unless defined $gval;
  439. next if $k eq "SCALAR" && ! defined $$gval; # always there
  440. # _dump can push into @post, so we hold our place using $postlen
  441. my $postlen = scalar @post;
  442. $post[$postlen] = "\*$sname = ";
  443. local ($s->{apad}) = " " x length($post[$postlen]) if $s->{indent} >= 2;
  444. $post[$postlen] .= $s->_dump($gval, "\*$sname\{$k\}");
  445. }
  446. }
  447. $out .= '*' . $sname;
  448. }
  449. elsif (!defined($val)) {
  450. $out .= "undef";
  451. }
  452. elsif ($val =~ /^(?:0|-?[1-9]\d{0,8})\z/) { # safe decimal number
  453. $out .= $val;
  454. }
  455. else { # string
  456. if ($s->{useqq} or $val =~ tr/\0-\377//c) {
  457. # Fall back to qq if there's unicode
  458. $out .= qquote($val, $s->{useqq});
  459. }
  460. else {
  461. $val =~ s/([\\\'])/\\$1/g;
  462. $out .= '\'' . $val . '\'';
  463. }
  464. }
  465. }
  466. if ($id) {
  467. # if we made it this far, $id was added to seen list at current
  468. # level, so remove it to get deep copies
  469. if ($s->{deepcopy}) {
  470. delete($s->{seen}{$id});
  471. }
  472. elsif ($name) {
  473. $s->{seen}{$id}[2] = 1;
  474. }
  475. }
  476. return $out;
  477. }
  478. #
  479. # non-OO style of earlier version
  480. #
  481. sub Dumper {
  482. return Data::Dumper->Dump([@_]);
  483. }
  484. # compat stub
  485. sub DumperX {
  486. return Data::Dumper->Dumpxs([@_], []);
  487. }
  488. sub Dumpf { return Data::Dumper->Dump(@_) }
  489. sub Dumpp { print Data::Dumper->Dump(@_) }
  490. #
  491. # reset the "seen" cache
  492. #
  493. sub Reset {
  494. my($s) = shift;
  495. $s->{seen} = {};
  496. return $s;
  497. }
  498. sub Indent {
  499. my($s, $v) = @_;
  500. if (defined($v)) {
  501. if ($v == 0) {
  502. $s->{xpad} = "";
  503. $s->{sep} = "";
  504. }
  505. else {
  506. $s->{xpad} = " ";
  507. $s->{sep} = "\n";
  508. }
  509. $s->{indent} = $v;
  510. return $s;
  511. }
  512. else {
  513. return $s->{indent};
  514. }
  515. }
  516. sub Pair {
  517. my($s, $v) = @_;
  518. defined($v) ? (($s->{pair} = $v), return $s) : $s->{pair};
  519. }
  520. sub Pad {
  521. my($s, $v) = @_;
  522. defined($v) ? (($s->{pad} = $v), return $s) : $s->{pad};
  523. }
  524. sub Varname {
  525. my($s, $v) = @_;
  526. defined($v) ? (($s->{varname} = $v), return $s) : $s->{varname};
  527. }
  528. sub Purity {
  529. my($s, $v) = @_;
  530. defined($v) ? (($s->{purity} = $v), return $s) : $s->{purity};
  531. }
  532. sub Useqq {
  533. my($s, $v) = @_;
  534. defined($v) ? (($s->{useqq} = $v), return $s) : $s->{useqq};
  535. }
  536. sub Terse {
  537. my($s, $v) = @_;
  538. defined($v) ? (($s->{terse} = $v), return $s) : $s->{terse};
  539. }
  540. sub Freezer {
  541. my($s, $v) = @_;
  542. defined($v) ? (($s->{freezer} = $v), return $s) : $s->{freezer};
  543. }
  544. sub Toaster {
  545. my($s, $v) = @_;
  546. defined($v) ? (($s->{toaster} = $v), return $s) : $s->{toaster};
  547. }
  548. sub Deepcopy {
  549. my($s, $v) = @_;
  550. defined($v) ? (($s->{deepcopy} = $v), return $s) : $s->{deepcopy};
  551. }
  552. sub Quotekeys {
  553. my($s, $v) = @_;
  554. defined($v) ? (($s->{quotekeys} = $v), return $s) : $s->{quotekeys};
  555. }
  556. sub Bless {
  557. my($s, $v) = @_;
  558. defined($v) ? (($s->{'bless'} = $v), return $s) : $s->{'bless'};
  559. }
  560. sub Maxdepth {
  561. my($s, $v) = @_;
  562. defined($v) ? (($s->{'maxdepth'} = $v), return $s) : $s->{'maxdepth'};
  563. }
  564. sub Useperl {
  565. my($s, $v) = @_;
  566. defined($v) ? (($s->{'useperl'} = $v), return $s) : $s->{'useperl'};
  567. }
  568. sub Sortkeys {
  569. my($s, $v) = @_;
  570. defined($v) ? (($s->{'sortkeys'} = $v), return $s) : $s->{'sortkeys'};
  571. }
  572. sub Deparse {
  573. my($s, $v) = @_;
  574. defined($v) ? (($s->{'deparse'} = $v), return $s) : $s->{'deparse'};
  575. }
  576. # used by qquote below
  577. my %esc = (
  578. "\a" => "\\a",
  579. "\b" => "\\b",
  580. "\t" => "\\t",
  581. "\n" => "\\n",
  582. "\f" => "\\f",
  583. "\r" => "\\r",
  584. "\e" => "\\e",
  585. );
  586. # put a string value in double quotes
  587. sub qquote {
  588. local($_) = shift;
  589. s/([\\\"\@\$])/\\$1/g;
  590. my $bytes; { use bytes; $bytes = length }
  591. s/([^\x00-\x7f])/'\x{'.sprintf("%x",ord($1)).'}'/ge if $bytes > length;
  592. return qq("$_") unless
  593. /[^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~]/; # fast exit
  594. my $high = shift || "";
  595. s/([\a\b\t\n\f\r\e])/$esc{$1}/g;
  596. if (ord('^')==94) { # ascii
  597. # no need for 3 digits in escape for these
  598. s/([\0-\037])(?!\d)/'\\'.sprintf('%o',ord($1))/eg;
  599. s/([\0-\037\177])/'\\'.sprintf('%03o',ord($1))/eg;
  600. # all but last branch below not supported --BEHAVIOR SUBJECT TO CHANGE--
  601. if ($high eq "iso8859") {
  602. s/([\200-\240])/'\\'.sprintf('%o',ord($1))/eg;
  603. } elsif ($high eq "utf8") {
  604. # use utf8;
  605. # $str =~ s/([^\040-\176])/sprintf "\\x{%04x}", ord($1)/ge;
  606. } elsif ($high eq "8bit") {
  607. # leave it as it is
  608. } else {
  609. s/([\200-\377])/'\\'.sprintf('%03o',ord($1))/eg;
  610. s/([^\040-\176])/sprintf "\\x{%04x}", ord($1)/ge;
  611. }
  612. }
  613. else { # ebcdic
  614. s{([^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])(?!\d)}
  615. {my $v = ord($1); '\\'.sprintf(($v <= 037 ? '%o' : '%03o'), $v)}eg;
  616. s{([^ !"\#\$%&'()*+,\-.\/0-9:;<=>?\@A-Z[\\\]^_`a-z{|}~])}
  617. {'\\'.sprintf('%03o',ord($1))}eg;
  618. }
  619. return qq("$_");
  620. }
  621. # helper sub to sort hash keys in Perl < 5.8.0 where we don't have
  622. # access to sortsv() from XS
  623. sub _sortkeys { [ sort keys %{$_[0]} ] }
  624. 1;
  625. __END__
  626. =head1 NAME
  627. Data::Dumper - stringified perl data structures, suitable for both printing and C<eval>
  628. =head1 SYNOPSIS
  629. use Data::Dumper;
  630. # simple procedural interface
  631. print Dumper($foo, $bar);
  632. # extended usage with names
  633. print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
  634. # configuration variables
  635. {
  636. local $Data::Dumper::Purity = 1;
  637. eval Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
  638. }
  639. # OO usage
  640. $d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]);
  641. ...
  642. print $d->Dump;
  643. ...
  644. $d->Purity(1)->Terse(1)->Deepcopy(1);
  645. eval $d->Dump;
  646. =head1 DESCRIPTION
  647. Given a list of scalars or reference variables, writes out their contents in
  648. perl syntax. The references can also be objects. The contents of each
  649. variable is output in a single Perl statement. Handles self-referential
  650. structures correctly.
  651. The return value can be C<eval>ed to get back an identical copy of the
  652. original reference structure.
  653. Any references that are the same as one of those passed in will be named
  654. C<$VAR>I<n> (where I<n> is a numeric suffix), and other duplicate references
  655. to substructures within C<$VAR>I<n> will be appropriately labeled using arrow
  656. notation. You can specify names for individual values to be dumped if you
  657. use the C<Dump()> method, or you can change the default C<$VAR> prefix to
  658. something else. See C<$Data::Dumper::Varname> and C<$Data::Dumper::Terse>
  659. below.
  660. The default output of self-referential structures can be C<eval>ed, but the
  661. nested references to C<$VAR>I<n> will be undefined, since a recursive
  662. structure cannot be constructed using one Perl statement. You should set the
  663. C<Purity> flag to 1 to get additional statements that will correctly fill in
  664. these references. Moreover, if C<eval>ed when strictures are in effect,
  665. you need to ensure that any variables it accesses are previously declared.
  666. In the extended usage form, the references to be dumped can be given
  667. user-specified names. If a name begins with a C<*>, the output will
  668. describe the dereferenced type of the supplied reference for hashes and
  669. arrays, and coderefs. Output of names will be avoided where possible if
  670. the C<Terse> flag is set.
  671. In many cases, methods that are used to set the internal state of the
  672. object will return the object itself, so method calls can be conveniently
  673. chained together.
  674. Several styles of output are possible, all controlled by setting
  675. the C<Indent> flag. See L<Configuration Variables or Methods> below
  676. for details.
  677. =head2 Methods
  678. =over 4
  679. =item I<PACKAGE>->new(I<ARRAYREF [>, I<ARRAYREF]>)
  680. Returns a newly created C<Data::Dumper> object. The first argument is an
  681. anonymous array of values to be dumped. The optional second argument is an
  682. anonymous array of names for the values. The names need not have a leading
  683. C<$> sign, and must be comprised of alphanumeric characters. You can begin
  684. a name with a C<*> to specify that the dereferenced type must be dumped
  685. instead of the reference itself, for ARRAY and HASH references.
  686. The prefix specified by C<$Data::Dumper::Varname> will be used with a
  687. numeric suffix if the name for a value is undefined.
  688. Data::Dumper will catalog all references encountered while dumping the
  689. values. Cross-references (in the form of names of substructures in perl
  690. syntax) will be inserted at all possible points, preserving any structural
  691. interdependencies in the original set of values. Structure traversal is
  692. depth-first, and proceeds in order from the first supplied value to
  693. the last.
  694. =item I<$OBJ>->Dump I<or> I<PACKAGE>->Dump(I<ARRAYREF [>, I<ARRAYREF]>)
  695. Returns the stringified form of the values stored in the object (preserving
  696. the order in which they were supplied to C<new>), subject to the
  697. configuration options below. In a list context, it returns a list
  698. of strings corresponding to the supplied values.
  699. The second form, for convenience, simply calls the C<new> method on its
  700. arguments before dumping the object immediately.
  701. =item I<$OBJ>->Seen(I<[HASHREF]>)
  702. Queries or adds to the internal table of already encountered references.
  703. You must use C<Reset> to explicitly clear the table if needed. Such
  704. references are not dumped; instead, their names are inserted wherever they
  705. are encountered subsequently. This is useful especially for properly
  706. dumping subroutine references.
  707. Expects an anonymous hash of name => value pairs. Same rules apply for names
  708. as in C<new>. If no argument is supplied, will return the "seen" list of
  709. name => value pairs, in a list context. Otherwise, returns the object
  710. itself.
  711. =item I<$OBJ>->Values(I<[ARRAYREF]>)
  712. Queries or replaces the internal array of values that will be dumped.
  713. When called without arguments, returns the values. Otherwise, returns the
  714. object itself.
  715. =item I<$OBJ>->Names(I<[ARRAYREF]>)
  716. Queries or replaces the internal array of user supplied names for the values
  717. that will be dumped. When called without arguments, returns the names.
  718. Otherwise, returns the object itself.
  719. =item I<$OBJ>->Reset
  720. Clears the internal table of "seen" references and returns the object
  721. itself.
  722. =back
  723. =head2 Functions
  724. =over 4
  725. =item Dumper(I<LIST>)
  726. Returns the stringified form of the values in the list, subject to the
  727. configuration options below. The values will be named C<$VAR>I<n> in the
  728. output, where I<n> is a numeric suffix. Will return a list of strings
  729. in a list context.
  730. =back
  731. =head2 Configuration Variables or Methods
  732. Several configuration variables can be used to control the kind of output
  733. generated when using the procedural interface. These variables are usually
  734. C<local>ized in a block so that other parts of the code are not affected by
  735. the change.
  736. These variables determine the default state of the object created by calling
  737. the C<new> method, but cannot be used to alter the state of the object
  738. thereafter. The equivalent method names should be used instead to query
  739. or set the internal state of the object.
  740. The method forms return the object itself when called with arguments,
  741. so that they can be chained together nicely.
  742. =over 4
  743. =item *
  744. $Data::Dumper::Indent I<or> I<$OBJ>->Indent(I<[NEWVAL]>)
  745. Controls the style of indentation. It can be set to 0, 1, 2 or 3. Style 0
  746. spews output without any newlines, indentation, or spaces between list
  747. items. It is the most compact format possible that can still be called
  748. valid perl. Style 1 outputs a readable form with newlines but no fancy
  749. indentation (each level in the structure is simply indented by a fixed
  750. amount of whitespace). Style 2 (the default) outputs a very readable form
  751. which takes into account the length of hash keys (so the hash value lines
  752. up). Style 3 is like style 2, but also annotates the elements of arrays
  753. with their index (but the comment is on its own line, so array output
  754. consumes twice the number of lines). Style 2 is the default.
  755. =item *
  756. $Data::Dumper::Purity I<or> I<$OBJ>->Purity(I<[NEWVAL]>)
  757. Controls the degree to which the output can be C<eval>ed to recreate the
  758. supplied reference structures. Setting it to 1 will output additional perl
  759. statements that will correctly recreate nested references. The default is
  760. 0.
  761. =item *
  762. $Data::Dumper::Pad I<or> I<$OBJ>->Pad(I<[NEWVAL]>)
  763. Specifies the string that will be prefixed to every line of the output.
  764. Empty string by default.
  765. =item *
  766. $Data::Dumper::Varname I<or> I<$OBJ>->Varname(I<[NEWVAL]>)
  767. Contains the prefix to use for tagging variable names in the output. The
  768. default is "VAR".
  769. =item *
  770. $Data::Dumper::Useqq I<or> I<$OBJ>->Useqq(I<[NEWVAL]>)
  771. When set, enables the use of double quotes for representing string values.
  772. Whitespace other than space will be represented as C<[\n\t\r]>, "unsafe"
  773. characters will be backslashed, and unprintable characters will be output as
  774. quoted octal integers. Since setting this variable imposes a performance
  775. penalty, the default is 0. C<Dump()> will run slower if this flag is set,
  776. since the fast XSUB implementation doesn't support it yet.
  777. =item *
  778. $Data::Dumper::Terse I<or> I<$OBJ>->Terse(I<[NEWVAL]>)
  779. When set, Data::Dumper will emit single, non-self-referential values as
  780. atoms/terms rather than statements. This means that the C<$VAR>I<n> names
  781. will be avoided where possible, but be advised that such output may not
  782. always be parseable by C<eval>.
  783. =item *
  784. $Data::Dumper::Freezer I<or> $I<OBJ>->Freezer(I<[NEWVAL]>)
  785. Can be set to a method name, or to an empty string to disable the feature.
  786. Data::Dumper will invoke that method via the object before attempting to
  787. stringify it. This method can alter the contents of the object (if, for
  788. instance, it contains data allocated from C), and even rebless it in a
  789. different package. The client is responsible for making sure the specified
  790. method can be called via the object, and that the object ends up containing
  791. only perl data types after the method has been called. Defaults to an empty
  792. string.
  793. If an object does not support the method specified (determined using
  794. UNIVERSAL::can()) then the call will be skipped. If the method dies a
  795. warning will be generated.
  796. =item *
  797. $Data::Dumper::Toaster I<or> $I<OBJ>->Toaster(I<[NEWVAL]>)
  798. Can be set to a method name, or to an empty string to disable the feature.
  799. Data::Dumper will emit a method call for any objects that are to be dumped
  800. using the syntax C<bless(DATA, CLASS)-E<gt>METHOD()>. Note that this means that
  801. the method specified will have to perform any modifications required on the
  802. object (like creating new state within it, and/or reblessing it in a
  803. different package) and then return it. The client is responsible for making
  804. sure the method can be called via the object, and that it returns a valid
  805. object. Defaults to an empty string.
  806. =item *
  807. $Data::Dumper::Deepcopy I<or> $I<OBJ>->Deepcopy(I<[NEWVAL]>)
  808. Can be set to a boolean value to enable deep copies of structures.
  809. Cross-referencing will then only be done when absolutely essential
  810. (i.e., to break reference cycles). Default is 0.
  811. =item *
  812. $Data::Dumper::Quotekeys I<or> $I<OBJ>->Quotekeys(I<[NEWVAL]>)
  813. Can be set to a boolean value to control whether hash keys are quoted.
  814. A false value will avoid quoting hash keys when it looks like a simple
  815. string. Default is 1, which will always enclose hash keys in quotes.
  816. =item *
  817. $Data::Dumper::Bless I<or> $I<OBJ>->Bless(I<[NEWVAL]>)
  818. Can be set to a string that specifies an alternative to the C<bless>
  819. builtin operator used to create objects. A function with the specified
  820. name should exist, and should accept the same arguments as the builtin.
  821. Default is C<bless>.
  822. =item *
  823. $Data::Dumper::Pair I<or> $I<OBJ>->Pair(I<[NEWVAL]>)
  824. Can be set to a string that specifies the separator between hash keys
  825. and values. To dump nested hash, array and scalar values to JavaScript,
  826. use: C<$Data::Dumper::Pair = ' : ';>. Implementing C<bless> in JavaScript
  827. is left as an exercise for the reader.
  828. A function with the specified name exists, and accepts the same arguments
  829. as the builtin.
  830. Default is: C< =E<gt> >.
  831. =item *
  832. $Data::Dumper::Maxdepth I<or> $I<OBJ>->Maxdepth(I<[NEWVAL]>)
  833. Can be set to a positive integer that specifies the depth beyond which
  834. which we don't venture into a structure. Has no effect when
  835. C<Data::Dumper::Purity> is set. (Useful in debugger when we often don't
  836. want to see more than enough). Default is 0, which means there is
  837. no maximum depth.
  838. =item *
  839. $Data::Dumper::Useperl I<or> $I<OBJ>->Useperl(I<[NEWVAL]>)
  840. Can be set to a boolean value which controls whether the pure Perl
  841. implementation of C<Data::Dumper> is used. The C<Data::Dumper> module is
  842. a dual implementation, with almost all functionality written in both
  843. pure Perl and also in XS ('C'). Since the XS version is much faster, it
  844. will always be used if possible. This option lets you override the
  845. default behavior, usually for testing purposes only. Default is 0, which
  846. means the XS implementation will be used if possible.
  847. =item *
  848. $Data::Dumper::Sortkeys I<or> $I<OBJ>->Sortkeys(I<[NEWVAL]>)
  849. Can be set to a boolean value to control whether hash keys are dumped in
  850. sorted order. A true value will cause the keys of all hashes to be
  851. dumped in Perl's default sort order. Can also be set to a subroutine
  852. reference which will be called for each hash that is dumped. In this
  853. case C<Data::Dumper> will call the subroutine once for each hash,
  854. passing it the reference of the hash. The purpose of the subroutine is
  855. to return a reference to an array of the keys that will be dumped, in
  856. the order that they should be dumped. Using this feature, you can
  857. control both the order of the keys, and which keys are actually used. In
  858. other words, this subroutine acts as a filter by which you can exclude
  859. certain keys from being dumped. Default is 0, which means that hash keys
  860. are not sorted.
  861. =item *
  862. $Data::Dumper::Deparse I<or> $I<OBJ>->Deparse(I<[NEWVAL]>)
  863. Can be set to a boolean value to control whether code references are
  864. turned into perl source code. If set to a true value, C<B::Deparse>
  865. will be used to get the source of the code reference. Using this option
  866. will force using the Perl implementation of the dumper, since the fast
  867. XSUB implementation doesn't support it.
  868. Caution : use this option only if you know that your coderefs will be
  869. properly reconstructed by C<B::Deparse>.
  870. =back
  871. =head2 Exports
  872. =over 4
  873. =item Dumper
  874. =back
  875. =head1 EXAMPLES
  876. Run these code snippets to get a quick feel for the behavior of this
  877. module. When you are through with these examples, you may want to
  878. add or change the various configuration variables described above,
  879. to see their behavior. (See the testsuite in the Data::Dumper
  880. distribution for more examples.)
  881. use Data::Dumper;
  882. package Foo;
  883. sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};
  884. package Fuz; # a weird REF-REF-SCALAR object
  885. sub new {bless \($_ = \ 'fu\'z'), $_[0]};
  886. package main;
  887. $foo = Foo->new;
  888. $fuz = Fuz->new;
  889. $boo = [ 1, [], "abcd", \*foo,
  890. {1 => 'a', 023 => 'b', 0x45 => 'c'},
  891. \\"p\q\'r", $foo, $fuz];
  892. ########
  893. # simple usage
  894. ########
  895. $bar = eval(Dumper($boo));
  896. print($@) if $@;
  897. print Dumper($boo), Dumper($bar); # pretty print (no array indices)
  898. $Data::Dumper::Terse = 1; # don't output names where feasible
  899. $Data::Dumper::Indent = 0; # turn off all pretty print
  900. print Dumper($boo), "\n";
  901. $Data::Dumper::Indent = 1; # mild pretty print
  902. print Dumper($boo);
  903. $Data::Dumper::Indent = 3; # pretty print with array indices
  904. print Dumper($boo);
  905. $Data::Dumper::Useqq = 1; # print strings in double quotes
  906. print Dumper($boo);
  907. $Data::Dumper::Pair = " : "; # specify hash key/value separator
  908. print Dumper($boo);
  909. ########
  910. # recursive structures
  911. ########
  912. @c = ('c');
  913. $c = \@c;
  914. $b = {};
  915. $a = [1, $b, $c];
  916. $b->{a} = $a;
  917. $b->{b} = $a->[1];
  918. $b->{c} = $a->[2];
  919. print Data::Dumper->Dump([$a,$b,$c], [qw(a b c)]);
  920. $Data::Dumper::Purity = 1; # fill in the holes for eval
  921. print Data::Dumper->Dump([$a, $b], [qw(*a b)]); # print as @a
  922. print Data::Dumper->Dump([$b, $a], [qw(*b a)]); # print as %b
  923. $Data::Dumper::Deepcopy = 1; # avoid cross-refs
  924. print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
  925. $Data::Dumper::Purity = 0; # avoid cross-refs
  926. print Data::Dumper->Dump([$b, $a], [qw(*b a)]);
  927. ########
  928. # deep structures
  929. ########
  930. $a = "pearl";
  931. $b = [ $a ];
  932. $c = { 'b' => $b };
  933. $d = [ $c ];
  934. $e = { 'd' => $d };
  935. $f = { 'e' => $e };
  936. print Data::Dumper->Dump([$f], [qw(f)]);
  937. $Data::Dumper::Maxdepth = 3; # no deeper than 3 refs down
  938. print Data::Dumper->Dump([$f], [qw(f)]);
  939. ########
  940. # object-oriented usage
  941. ########
  942. $d = Data::Dumper->new([$a,$b], [qw(a b)]);
  943. $d->Seen({'*c' => $c}); # stash a ref without printing it
  944. $d->Indent(3);
  945. print $d->Dump;
  946. $d->Reset->Purity(0); # empty the seen cache
  947. print join "----\n", $d->Dump;
  948. ########
  949. # persistence
  950. ########
  951. package Foo;
  952. sub new { bless { state => 'awake' }, shift }
  953. sub Freeze {
  954. my $s = shift;
  955. print STDERR "preparing to sleep\n";
  956. $s->{state} = 'asleep';
  957. return bless $s, 'Foo::ZZZ';
  958. }
  959. package Foo::ZZZ;
  960. sub Thaw {
  961. my $s = shift;
  962. print STDERR "waking up\n";
  963. $s->{state} = 'awake';
  964. return bless $s, 'Foo';
  965. }
  966. package Foo;
  967. use Data::Dumper;
  968. $a = Foo->new;
  969. $b = Data::Dumper->new([$a], ['c']);
  970. $b->Freezer('Freeze');
  971. $b->Toaster('Thaw');
  972. $c = $b->Dump;
  973. print $c;
  974. $d = eval $c;
  975. print Data::Dumper->Dump([$d], ['d']);
  976. ########
  977. # symbol substitution (useful for recreating CODE refs)
  978. ########
  979. sub foo { print "foo speaking\n" }
  980. *other = \&foo;
  981. $bar = [ \&other ];
  982. $d = Data::Dumper->new([\&other,$bar],['*other','bar']);
  983. $d->Seen({ '*foo' => \&foo });
  984. print $d->Dump;
  985. ########
  986. # sorting and filtering hash keys
  987. ########
  988. $Data::Dumper::Sortkeys = \&my_filter;
  989. my $foo = { map { (ord, "$_$_$_") } 'I'..'Q' };
  990. my $bar = { %$foo };
  991. my $baz = { reverse %$foo };
  992. print Dumper [ $foo, $bar, $baz ];
  993. sub my_filter {
  994. my ($hash) = @_;
  995. # return an array ref containing the hash keys to dump
  996. # in the order that you want them to be dumped
  997. return [
  998. # Sort the keys of %$foo in reverse numeric order
  999. $hash eq $foo ? (sort {$b <=> $a} keys %$hash) :
  1000. # Only dump the odd number keys of %$bar
  1001. $hash eq $bar ? (grep {$_ % 2} keys %$hash) :
  1002. # Sort keys in default order for all other hashes
  1003. (sort keys %$hash)
  1004. ];
  1005. }
  1006. =head1 BUGS
  1007. Due to limitations of Perl subroutine call semantics, you cannot pass an
  1008. array or hash. Prepend it with a C<\> to pass its reference instead. This
  1009. will be remedied in time, now that Perl has subroutine prototypes.
  1010. For now, you need to use the extended usage form, and prepend the
  1011. name with a C<*> to output it as a hash or array.
  1012. C<Data::Dumper> cheats with CODE references. If a code reference is
  1013. encountered in the structure being processed (and if you haven't set
  1014. the C<Deparse> flag), an anonymous subroutine that
  1015. contains the string '"DUMMY"' will be inserted in its place, and a warning
  1016. will be printed if C<Purity> is set. You can C<eval> the result, but bear
  1017. in mind that the anonymous sub that gets created is just a placeholder.
  1018. Someday, perl will have a switch to cache-on-demand the string
  1019. representation of a compiled piece of code, I hope. If you have prior
  1020. knowledge of all the code refs that your data structures are likely
  1021. to have, you can use the C<Seen> method to pre-seed the internal reference
  1022. table and make the dumped output point to them, instead. See L</EXAMPLES>
  1023. above.
  1024. The C<Useqq> and C<Deparse> flags makes Dump() run slower, since the
  1025. XSUB implementation does not support them.
  1026. SCALAR objects have the weirdest looking C<bless> workaround.
  1027. Pure Perl version of C<Data::Dumper> escapes UTF-8 strings correctly
  1028. only in Perl 5.8.0 and later.
  1029. =head2 NOTE
  1030. Starting from Perl 5.8.1 different runs of Perl will have different
  1031. ordering of hash keys. The change was done for greater security,
  1032. see L<perlsec/"Algorithmic Complexity Attacks">. This means that
  1033. different runs of Perl will have different Data::Dumper outputs if
  1034. the data contains hashes. If you need to have identical Data::Dumper
  1035. outputs from different runs of Perl, use the environment variable
  1036. PERL_HASH_SEED, see L<perlrun/PERL_HASH_SEED>. Using this restores
  1037. the old (platform-specific) ordering: an even prettier solution might
  1038. be to use the C<Sortkeys> filter of Data::Dumper.
  1039. =head1 AUTHOR
  1040. Gurusamy Sarathy gsar@activestate.com
  1041. Copyright (c) 1996-98 Gurusamy Sarathy. All rights reserved.
  1042. This program is free software; you can redistribute it and/or
  1043. modify it under the same terms as Perl itself.
  1044. =head1 VERSION
  1045. Version 2.121 (Aug 24 2003)
  1046. =head1 SEE ALSO
  1047. perl(1)
  1048. =cut