File: JSON.pm

package info (click to toggle)
libspreadsheet-wright-perl 0.107-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 228 kB
  • sloc: perl: 1,008; makefile: 2
file content (90 lines) | stat: -rw-r--r-- 1,655 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package Spreadsheet::Wright::JSON;

use 5.010;
use strict;
use warnings;
no warnings qw( uninitialized numeric );

BEGIN {
	$Spreadsheet::Wright::JSON::VERSION   = '0.107';
	$Spreadsheet::Wright::JSON::AUTHORITY = 'cpan:TOBYINK';
}

use Carp;
use JSON;

use parent qw(Spreadsheet::Wright);

sub new
{
	my ($class, %args) = @_;
	my $self = bless { 'options' => \%args }, $class;
	$self->{'_FILENAME'} = $args{'file'} // $args{'filename'}
		or croak "Need filename.";
	$self->{'_WORKSHEET'} = $args{'sheet'} // 'Sheet1';
	return $self;
}

sub addsheet
{
	my ($self, $caption) = @_;
	$caption //= 'Sheet' . (1 + scalar keys %{$self->{'data'}});
	
	if (defined $self->{'data'}->{$caption})
	{
		my $i    = 2;
		my $base = $caption;
		
		ALTERNATIVE: while (1)
		{
			$caption = "$base ($i)";
			last ALTERNATIVE unless defined $self->{'data'}->{$caption};
			$i++;
		}
	}
	
	$self->{'_WORKSHEET'} = $caption;
	return $self;
}

sub _add_prepared_row
{
	my $self = shift;
	
	my @texts;
	foreach my $cell (@_)
	{
		my $content = $cell->{'content'};
		$content = sprintf($content, $cell->{'sprintf'})
			if $cell->{'sprintf'};
		push @texts, $content;
	}
	push @{ $self->{'data'}->{$self->{'_WORKSHEET'}} }, [@texts];
	
	return $self;
}

sub close
{
	my $self=shift;
	return if $self->{'_CLOSED'};
	
	if (1 == scalar keys %{$self->{'data'}})
	{
		$self->{'_FH'}->print(
			to_json($self->{'data'}->{$self->{'_WORKSHEET'}}, $self->{'options'}{'json_options'})
			);
	}
	else
	{
		$self->{'_FH'}->print(
			to_json($self->{'data'}, $self->{'options'}{'json_options'})
			);
	}
	
	$self->{'_FH'}->close if $self->{'_FH'};
	$self->{'_CLOSED'}=1;
	return $self;
}

1;