From b182c0090e9a560549f85490362fb354d077b916 Mon Sep 17 00:00:00 2001 From: Ricardo Signes Date: Tue, 4 May 2010 16:25:13 -0400 Subject: [PATCH] stringify SCALAR, REF, and undef --- Changes | 2 ++ lib/String/Flogger.pm | 13 ++++++++++--- t/basic.t | 30 ++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 t/basic.t diff --git a/Changes b/Changes index 7907a20..f95ea52 100644 --- a/Changes +++ b/Changes @@ -1,6 +1,8 @@ Revision history for String-Flogger {{$NEXT}} + better stringification of unblessed scalar refs (to ref(...)) + better stringification of undef (to {{null}}) 1.101170 2010-04-27 14:59:36 America/New_York fix a typo in docs (thanks MJD) diff --git a/lib/String/Flogger.pm b/lib/String/Flogger.pm index ef2d174..97a5bf7 100644 --- a/lib/String/Flogger.pm +++ b/lib/String/Flogger.pm @@ -42,8 +42,10 @@ The above will output: sub _encrefs { my ($self, $messages) = @_; - return map { ref $_ ? ('{{' . $self->_stringify_ref($_) . '}}') : $_ } - map { blessed($_) ? sprintf('obj(%s)', "$_") : $_ } + return map { blessed($_) ? sprintf('obj(%s)', "$_") + : ref $_ ? $self->_stringify_ref($_) + : defined $_ ? $_ + : '{{null}}' } map { _CODELIKE($_) ? scalar $_->() : $_ } @$messages; } @@ -52,6 +54,11 @@ my $JSON; sub _stringify_ref { my ($self, $ref) = @_; + if (ref $ref eq 'SCALAR' or ref $ref eq 'REF') { + my ($str) = $self->_encrefs([ $$ref ]); + return "ref($str)"; + } + require JSON; $JSON ||= JSON->new ->ascii(1) @@ -60,7 +67,7 @@ sub _stringify_ref { ->space_after(1) ->convert_blessed(1); - return $JSON->encode($ref) + return '{{' . $JSON->encode($ref) . '}}' } sub flog { diff --git a/t/basic.t b/t/basic.t new file mode 100644 index 0000000..3bbdf90 --- /dev/null +++ b/t/basic.t @@ -0,0 +1,30 @@ +#!perl +use strict; +use warnings; +use Test::More tests => 4; +use String::Flogger qw(flog); + +is( + flog([ 'foo %s bar', undef ]), + 'foo {{null}} bar', + "%s <- undef", +); + +is( + flog([ 'foo %s bar', \undef ]), + 'foo ref({{null}}) bar', + "%s <- \\undef", +); + +is( + flog([ 'foo %s bar', \1 ]), + 'foo ref(1) bar', + "%s <- \\1", +); + +is( + flog([ 'foo %s bar', \\1 ]), + 'foo ref(ref(1)) bar', + "%s <- \\\\1", +); +