Perl:With Text :: CSV可以写出一个哈希ref吗? [英] Perl: With Text::CSV can I write out a hash ref?

查看:197
本文介绍了Perl:With Text :: CSV可以写出一个哈希ref吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Perl脚本,读取CSV文件,更改原始的列名称,添加新的(输出CSV列名存储在数组,header_line),为每一行读取添加新的字段值,然后写出一个新的CSV文件。

I have a Perl script that reads in a CSV file, changes the columns names of the original, adds new ones (output CSV column names are stored in the array, header_line), adds new field values for each row read, and then writes out a new CSV file.

感谢@harleypig对我最后的问题,我想使用:

Thanks to a comment by @harleypig on my last question, I'd like to use:

$csv_i->column_names( @header_line);
$row = $csv_i->getline_hr($fh_i)

使用有意义的名称而不是魔术数字轻松访问行字段。例如:

because this lets me easily access row fields using meaningful names rather than magic numbers. For example:

$row->{ 'name' } = get_fullname($row->{ 'name' });

现在唯一的问题是,写出行的最好方法是什么?以前,我使用了:

The only problem now is, what's the best way to write out the line? Previously, I used:

$csv_o->print( $fh_o, $row ); 

但是失败是因为它需要一个数组引用。如何使用csv_o对象写出散列引用?

But that fails because it expects an array ref. How do I write out the hash ref using the csv_o object?

推荐答案

使用散列片

$csv_o->print( $fh_o, [ @$row{@header_line} ] );

map 切片更快:

use Benchmark 'cmpthese';

my @header_line = qw(a b c d e f g);
my $row = { map { $_ => $_ } @header_line };

my $array;

cmpthese(-3, {
  slice => sub {
    $array = [ @$row{@header_line} ];
  },

 map => sub {
    $array = [ map { $row->{$_} } @header_line ];
  },
});

给我:

          Rate   map slice
map   282855/s    --  -42%
slice 487898/s   72%    --

这篇关于Perl:With Text :: CSV可以写出一个哈希ref吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆