2013年1月1日火曜日

[Perl]CSV

読み込み
test00.pl
# -*- coding: utf-8 -*-
use strict;
use utf8;

open(IN, 'sample.csv');
while () {
    chomp;
    my @r = split(/,/, $_);
    print "\$r[0] = " . $r[0] . " ";
    print "\$r[1] = " . $r[1] . "\n";
}
close(IN);
sample.csv
1,dog
2,cat
実行結果
$r[0] = 1 $r[1] = dog
$r[0] = 2 $r[1] = cat
書き込み
test01.pl
# -*- coding: utf-8 -*-
use strict;
use utf8;

open(IN, 'sample.csv');
while () {
    chomp;
    my @r = split(/,/, $_);
    print "\$r[0] = " . $r[0] . " ";
    print "\$r[1] = " . $r[1] . "\n";
}
close(IN);

open(OUT, '> out.csv');
my @row = (1, 'elephant');
print $row[0] . ", " . $row[1] . "\n";
my $r = join(',', @row) . "\n";
print(OUT $r);
@row = (2, 'giraffe');
print $row[0] . ", " . $row[1] . "\n";
$r = join(',', @row) . "\n";
print(OUT $r);
close(OUT);
実行結果
out.csv
1,elephant
2,giraffe

0 件のコメント:

コメントを投稿