nomurabbitのブログ

nomurabbitのブログはITを中心にした技術ブログです。

nomurabbitのブログ

Perlでデータを自作クラスの配列として扱う話

これまでの記事でやったようなことをPerlでやってみた。

多分こんな感じかな?という手探り感満載のコードになりましたが、

やってることは以下

1)ファイルの読み込み各行を配列に格納

2)配列に格納された各行をtabで分割し、データ格納用クラスに格納

3)データ格納用クラスの配列を返し表示


<test.pl>

#!perl\bin\perl

use Encode;

################################################################
# DataClassの定義
#
package DataClass;

#---------------------------------------------------------------
# コンストラクタ
#
sub new
{
	my $this = shift;
	my $args =
	{
		ISBN10 => shift,
		ISBN13 => shift,
		TITLE  => shift
	};
	bless $args, $this ;
}

#---------------------------------------------------------------
# アクセサメソッド
#
sub GetIsbn10
{
	my $this = shift;
	return $this->{ISBN10};
}

sub GetIsbn13
{
	my $this = shift;
	return $this->{ISBN13};
}

sub GetTitle
{
	my $this = shift;
	return $this->{TITLE};
}

################################################################
# MethodClassの定義
#
package MethodClass;

use Encode;

#---------------------------------------------------------------
# コンストラクタ
#
sub new
{
	my $this = shift;
	my $args =
	{
		PATH => shift
	};
	bless $args, $this;
}

#---------------------------------------------------------------
# アクセサメソッド
#
sub GetPath
{
	my $this = shift;
	return $this->{PATH};
}

#---------------------------------------------------------------
# クラスメソッド
#
sub GetDataList
{
	# 初期化、変数の定義
	my $this            = shift;
	my $filePath        = "<" . $this->{PATH};
	my @dataList;
	
	open FH, $filePath;
	foreach(<FH>)
	{
		my $str = decode("utf8", $_);
		push(@dataList, $str);
	}
	close FH;

	return @dataList;
}

sub GetCommonDataList
{
	# 初期化、変数の定義
	my $this     = shift;
	my @dataList = $this->GetDataList;
	my @commonDataList;
	
	foreach(@dataList)
	{
		my @tempCommonData = split(/\t/, $_);
		push(@commonDataList, new DataClass($tempCommonData[0], $tempCommonData[1], $tempCommonData[2]));
	}

	return @commonDataList;
}

################################################################
# MainClassの定義
#
package main;

#--------------------------------------------------------------
# 変数の定義
#
my $path = "C:\\test.txt";

#--------------------------------------------------------------
# インスタンスの生成
#
my $method         = new MethodClass($path);
my @commonDataList = $method->GetCommonDataList;

#--------------------------------------------------------------
# データ出力
#
foreach(@commonDataList)
{
	print encode("shiftjis", $_->GetTitle . "\t" . $_->GetIsbn10 . "\t" . $_->GetIsbn13 . "\n");
}

こんな感じで書けました!

書きやすさでいえば

C# > F# >> Perl

個人的な慣れもあると思いますけどね!