In Perl, how do I import a CSV sample, do basic text manipulation, and then save it back to CSV?

I decided to try and learn Perl, and currently I need to process several CSV files.

To get started with more text processing, I first need some basic code that:

  • Imports a local CSV
  • Does the main text manipulation
  • Save received modified values

Import / process / export should support 1000 rows and 20+ columns. Go on to supply a sample CSV file, but feel free to provide it in your answer.

SAMPLE CSV FILE:

"EmployeeName","OfficeHistory","JobLevelHistory"
"John Smith",501,"Engineer"
"John Smith",601,"Senior Engineer"
"John Smith",701,"Manager"
"Alex Button",601,"Senior Assistant"
"Alex Button",454,"Manager"

- , - . , , . , , . (. , Perl .)

+3
2

:: CSV_XS :: CSV.

- , . CSV - , (RFC 4180), post hoc, , , Microsoft, -. MS , CSV, MS.


:: CSV

#!/usr/bin/env perl
use strict;
use warnings;
use Text::CSV;

my @rows;

# Read the CSV file
{
    my $csv = Text::CSV->new()
        or die "Cannot use Text::CSV ($!)";
    my $file = "data.csv";
    open my $fh, '<', $file
        or die "Cannot open $file ($!)";

    while (my $row = $csv->getline($fh))
    {
        push @rows, $row;
    }
    $csv->eof or $csv->error_diag();

    close $fh
        or die "Failed to close $file ($!)";
}

# Munge the data
{
    foreach my $row (@rows)
    {
        foreach my $col (@{$row})
        {
            $col = uc($col);
        }
        print "\n";
    }
}

# Write the data
{
    my $csv = Text::CSV->new()
        or die "Cannot use Text::CSV ($!)";
    my $file = "output.csv";
    open my $fh, '>', $file
        or die "Cannot open $file ($!)";
    $csv->eol("\n");
    foreach my $row (@rows)
    {

        $csv->print($fh, \@{$row})
            or die "Failed to write $file ($!)";
    }
    close $fh
        or die "Failed to close $file ($!)";
}

,

EMPLOYEENAME,OFFICEHISTORY,JOBLEVELHISTORY
"JOHN SMITH",501,ENGINEER
"JOHN SMITH",601,"SENIOR ENGINEER"
"JOHN SMITH",701,MANAGER
"ALEX BUTTON",601,"SENIOR ASSISTANT"
"ALEX BUTTON",454,MANAGER
+8

:: xSV , , , Text:: CSV [_XS], .

,

my $csv = Text::xSV->new(filename => "file.csv");

my $csv = Text::xSV->new;

, ( ), , .

,

while (my @row = $csv->get_row) {
  # Do stuff with the fields in @row
}

, , ,

$csv->read_header;

, :

while (my %row = $csv->fetchrow_hash) {
  print $row{EmployeeName};
}

. , , - . , Text::xSV, .

"uppercase all" :

#!/usr/bin/perl
use strict;
use warnings;
use Text::xSV;

my $in = Text::xSV->new("data.csv");
my $out = Text::xSV->new("output.csv");

while (my $row = $in->get_row) {
    for my $col (@row) {
        $col = uc $col;
    }
    $out->print_row(@row);
}

script, Text::xSV , , ( open) .

+2

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


All Articles