Skip to content

Instantly share code, notes, and snippets.

@zmughal
Created February 18, 2013 17:44
Show Gist options
  • Save zmughal/4979167 to your computer and use it in GitHub Desktop.
Save zmughal/4979167 to your computer and use it in GitHub Desktop.
package Data::Printer::Filter::PDL::Color;
use strict;
use warnings;
use Data::Printer::Filter;
use Term::ANSIColor;
# modified from <https://gist.github.com/2990606>
filter 'PDL', \&pdl_filter;
filter 'PDL::Char', \&pdl_filter; # TODO this does not seem to work
sub pdl_filter {
my ($self, $props) = @_;
################################################
# Get Data, Build Structure #
# add new things as [ tag => data ] to @data #
################################################
my @data;
if($self->nelem < 10_000) {
(my $string = $self->string) =~ s,^\n|\n$,,gs;
# TODO if PDL::Char also show $p->PDL::string()
push @data, [ 'Data' => color_pdl_string(['magenta'], $string) ];
}
# type
push @data, [ Type => colored(['black on_red'], $self->type->realctype) ];
# shape
push @data, [ Shape => color_pdl_string(['cyan'], $self->shape->string) ];
# elements
push @data, [ Nelem => colored(['bright_yellow'], $self->nelem) ];
# min and max
my ($min, $max) = $self->minmax;
push @data, [ Min => colored(['bright_red'], $min) ];
push @data, [ Max => colored(['bright_blue'], $max) ];
# bad?
my $bad_flag = $self->badflag;
$self->check_badflag;
push @data, [ Badflag => color_bad_bool($bad_flag) ];
push @data, [ 'Has Bads' => color_bad_bool($self->badflag) ];
$self->badflag($bad_flag);
#####################
# Format the Output #
#####################
$props ||= {};
my $indent = defined $props->{indent} ? $props->{indent} : 4;
my $max_tag_length = List::Util::max map { length $_->[0] } @data;
my $tag_format = ' ' x $indent . '%-' . $max_tag_length . 's : ';
(my $empty_tag = sprintf($tag_format, "")) =~ s,:, ,;
my @formatted =
map {
$_->[1] =~ s,\n,\n$empty_tag,gs;
sprintf($tag_format, $_->[0]) . $_->[1]
}
@data;
my $data = ref($self) . " {\n";
$data .= join "\n", @formatted;
$data .= "\n}";
return $data;
};
sub color_pdl_string {
my ($color, $pdl) = @_;
$pdl =~ s/\[(.*)\]/"[".colored($color, $1)."]"/eg;
$pdl =~ s/^([^\[]+)$/colored($color, $1)/eg;
$pdl =~ s/^\s*\[|\]$/colored(['bright_green'], $&)/emg;
return $pdl;
}
sub color_bad_bool {
my $bool = shift;
return $bool ? colored(['red'],"Yes") : colored(['green'],"No");
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment