Skip to content

Commit

Permalink
stringify SCALAR, REF, and undef
Browse files Browse the repository at this point in the history
  • Loading branch information
rjbs committed May 4, 2010
1 parent 03168be commit b182c00
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
2 changes: 2 additions & 0 deletions 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)
Expand Down
13 changes: 10 additions & 3 deletions lib/String/Flogger.pm
Expand Up @@ -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;
}
Expand All @@ -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)
Expand All @@ -60,7 +67,7 @@ sub _stringify_ref {
->space_after(1)
->convert_blessed(1);

return $JSON->encode($ref)
return '{{' . $JSON->encode($ref) . '}}'
}

sub flog {
Expand Down
30 changes: 30 additions & 0 deletions 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",
);

0 comments on commit b182c00

Please sign in to comment.