Tripletail

 view release on metacpan or  search on metacpan

lib/Tripletail/CSV.pm  view on Meta::CPAN

# -----------------------------------------------------------------------------
# Tripletail::CSV - ファイルハンドルからのデータの読み込み
# -----------------------------------------------------------------------------
package Tripletail::CSV;
use strict;
use warnings;
use IO::Handle ();
use IO::Scalar ();
use version 0.77;


1;

sub _new {
	my $class = shift;

	my $this = bless {} => $class;

	eval {
		require Text::CSV_XS;
	};
	if ($@) {
		die __PACKAGE__."#new: Text::CSV_XS is unavailable. (Text::CSV_XSが使用できません)\n";
	}

	my $opts = do {
		if (Text::CSV_XS->VERSION >= version->parse('1.02')) {
			{
				binary => 1,
				decode_utf8 => 0,
			};
		} else {
			{
				binary => 1,
			};
		}
	};

	$this->{csv} = Text::CSV_XS->new($opts);

	$this;
}

sub parseCsv {
	my $this = shift;
	my $src = shift;

	my $fh;
	if (ref $src) {
		$fh = $src;
	}
	else {
		$fh = IO::Scalar->new(\$src);
	}

	Tripletail::CSV::Parser->_new($this, $fh);
}

sub makeCsv {
	my $this = shift;
	my $row = shift;

	if (ref($row) ne 'ARRAY') {
		die __PACKAGE__."#makeCsv: arg[1] is not an ARRAY ref. (第1引数が配列のリファレンスではありません)\n";
	}

	$this->{csv}->combine(@$row);
	$this->{csv}->string;
}

package Tripletail::CSV::Parser;
use strict;
use warnings;

sub _new {
	my $class = shift;
	my $csv = shift;
	my $fh = shift;

	my $this = bless {} => $class;
	$this->{csv} = $csv;
	$this->{fh} = $fh;

	$this;
}

sub next {
	my $this = shift;

	if ($this->{fh}->eof) {
		return;
	}
	else {
		if (my $row = $this->{csv}{csv}->getline($this->{fh})) {
			$row;
		}
		else {
			die __PACKAGE__."#next: parse error. (不正なCSV形式です)\n";
		}
	}
}

__END__

=encoding utf-8

=for stopwords
	CSV
	YMIRLINK

=head1 NAME

Tripletail::CSV - CSV のパースと生成

=head1 SYNOPSIS

  # パース
  my $csv = $TL->getCsv;
  my $parser = $csv->parseCsv($CGI->getFile('upload'));
  
  while (my $row = $parser->next) {
      # $row: ['カラム1', 'カラム2', ...]
  }
  

  # 生成
  $TL->print($csv->makeCsv([ qw(aaa bbb ccc) ]), "\n");
  $TL->print($csv->makeCsv([ qw(aaa bbb ccc) ]), "\n");

=head1 DESCRIPTION

CSV のパースと生成を行う為のクラス。
カンマを含むカラム、改行コードを含むカラム等も
正しく処理する事が出来る。

文字列のパースの他に、ファイルハンドルからのパースも可能。

=head2 METHODS

=over 4



( run in 1.141 second using v1.01-cache-2.11-cpan-c221a9de4ec )