Gnuplot-Builder

 view release on metacpan or  search on metacpan

lib/Gnuplot/Builder/Dataset.pm  view on Meta::CPAN

package Gnuplot::Builder::Dataset;
use strict;
use warnings;
use Gnuplot::Builder::PrototypedData;
use Scalar::Util qw(weaken blessed);
use Carp;
use overload '""' => 'to_string';

sub new {
    my ($class, $source, @set_option_args) = @_;
    my $self = bless {
        pdata => undef,
        pdata_join => undef,  ## deprecated. should be removed in the future.
        parent => undef,
    }, $class;
    $self->_init_pdata();
    if(defined $source) {
        $self->set_source($source);
    }
    if(@set_option_args) {
        $self->set_option(@set_option_args);
    }
    return $self;
}

sub new_file {
    my ($class, $filename, @set_option_args) = @_;
    return $class->new->set_file($filename)->set_option(@set_option_args);
}

sub new_data {
    my ($class, $data_provider, @set_option_args) = @_;
    return $class->new->set_file('-')->set_data($data_provider)->set_option(@set_option_args);
}

sub _init_pdata {
    my ($self) = @_;
    weaken $self;
    $self->{pdata} = Gnuplot::Builder::PrototypedData->new(
        entry_evaluator => sub {
            my ($key, $coderef) = @_;
            return $coderef->($self, $key);
        },
        attribute_evaluator => { source => sub {
            my ($key, $coderef) = @_;
            return $coderef->($self);
        } },
    );
    $self->{pdata_join} = Gnuplot::Builder::PrototypedData->new();
}

sub to_string {
    my ($self) = @_;
    my @words = ();
    push @words, $self->get_source;
    $self->{pdata}->each_resolved_entry(sub {
        my ($name, $values_arrayref) = @_;
        my @values = grep { defined($_) } @$values_arrayref;
        return if !@values;
        my $join = $self->{pdata_join}->get_resolved_attribute($name);
        if(defined $join) {
            push @words, $name, join($join, @values);
        }else {
            push @words, $name, @values;
        }
    });
    return join " ", grep { defined($_) && "$_" ne "" } @words;
}

*params_string = *to_string;

sub set_source {
    my ($self, $source) = @_;
    $self->{pdata}->set_attribute(
        key => "source", value => $source
    );
    return $self;
}

sub setq_source {
    my ($self, $source) = @_;
    $self->{pdata}->set_attribute(
        key => "source", value => $source, quote => 1,
    );
    return $self;
}

*set_file = *setq_source;

sub get_source {
    my ($self) = @_;
    return $self->{pdata}->get_resolved_attribute("source");
}

sub delete_source {
    my ($self) = @_;
    $self->{pdata}->delete_attribute("source");
    return $self;



( run in 0.555 second using v1.01-cache-2.11-cpan-39bf76dae61 )