Perl: With text :: CSV, can I write a hash code?

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

Thanks to the comment by @harleypig on my last question , I would like to use:

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

because it allows me to easily access string strings using meaningful names rather than magic numbers. For instance:

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

The only problem is what is the best way to write a string? I used to use:

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

But this fails because it expects an array of ref. How to write hash ref using csv_o object?

+1
2

-:

$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%    --
+4

, , . hashref ( ), :

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

Source: https://habr.com/ru/post/1774340/


All Articles