CSV(3pm)

πŸ“¦
version 1.03 Β· 5 versions
, in debian bookworm, ubuntu jammy, ubuntu noble

CSV(3pm) πŸ’–

okay bestie, welcome to CSV(3pm), a User Contributed Perl Documentation page, and it's literally all about parsing and writing CSV files with objects. pull up a chair, grab a boba, we're doing this πŸ§‹βœ¨


🌸 NAME 🌸

Class::CSV β€” Class based CSV parser/writer. that's it, that's the whole vibe. πŸ’…


✨ SYNOPSIS ✨

here's the main character energy in code form, copied exactly because I would never mess with your code:

use Class::CSV;

my $csv = Class::CSV->parse(
  filename => 'test.csv',
  fields   => [qw/item qty sub_total/]
);

foreach my $line (@{$csv->lines()}) {
  $line->sub_total('$'. sprintf("%0.2f", $line->sub_total()));

  print 'Item:     '. $line->item(). "\n".
        'Qty:      '. $line->qty(). "\n".
        'SubTotal: '. $line->sub_total(). "\n";
}

my $cvs_as_string = $csv->string();

$csv->print();

my $csv = Class::CSV->new(
  fields         => [qw/userid username/],
  line_separator => "\r\n";
);

$csv->add_line([2063, 'testuser']);
$csv->add_line({
  userid   => 2064,
  username => 'testuser2'
});

πŸ’– DESCRIPTION πŸ’–

so what does this module even do? two things, and it does them well: it makes objects out of CSV files, and it makes CSV files out of objects. circular queen behavior πŸ¦‹

under the hood it's Text::CSV_XS doing the actual parsing and line-making, so any limitations Text::CSV_XS has are of course inherant in this module. no cap, that's just how it is.

πŸ“¦ EXPORT πŸ“¦

None by default. nothing gets exported, she's self-contained, she's independent πŸ’…


πŸŽ€ METHOD πŸŽ€

πŸ›  CONSTRUCTOR πŸ› 

parse

the parse constructor takes a hash as its paramater, and all the lil options that can live inside that hash are detailed below. πŸ‘‡

Required Options 🌟

  • fields β€” an array ref containing the list of field names to use for each row. heads up though: there are some reserved words that cannot be used as field names. there's no checking done for this at the moment, but it is something to be aware of, fr fr. the reserved field names are: "string", "set", "get". also, field names cannot contain whitespace or any characters that would not be allowed in a method name. periodt. πŸ’€

Source Options (only one of these is needed) πŸ“

  • filename β€” the path of the CSV file to be opened and parsed. classic.
  • filehandle β€” the file handle of the CSV file to be parsed. for when you already have it open, iykyk.
  • objects β€” an array ref of objects (e.g. Class::DBI objects). for this to work properly, the field names provided in fields need to correspond to the field names of the objects in the array ref. matchy matchy ✨
  • classdbi_objects β€” depreciated, use objects instead. using classdbi_objects will still work but its advisable to update your code. bestie, it's giving legacy, let it go πŸ™ˆ

Optional Options πŸŽ€

  • line_separator β€” the line seperator to be included at the end of every line, defaulting to "\n" (unix carriage return). the little detail that keeps everything tidy 🌈

new

the new constructor takes a hash as its paramater, and the same options detailed in parse apply to new β€” however no Source Options can be used. this constructor creates a blank CSV object of which lines can be added via add_line. a fresh start, a clean slate, main character origin story πŸ¦‹


πŸ” ACCESSING πŸ”

lines

returns an array ref containing objects of each CSV line (made via Class::Accessor). the field names given upon construction are available as accessors and can be set or get. for more information please see the notes below or the perldoc for Class::Accessor. the lines accessor is also able to be updated/retrieved in the same way as individual lines fields (examples below). πŸ‘‘

Example πŸ’«

retrieving the lines:

my @lines = @{$csv->lines()};

removing the first line:

pop @lines;

$csv->lines(\@lines);

sorting the lines:

@lines = sort { $a->userid() <=> $b->userid() } @lines:

$csv->lines(\@lines);

sorting the lines (all-in-one way):

$csv->lines([ sort { $a->userid() <=> $b->userid() } @{$csv->lines()} ]);

Retrieving a fields value 🌸

there is two ways to retrieve a fields value (as documented in Class::Accessor). firstly you can call the field name on the object, and secondly you can call "get" on the object with the field name as the argument (multiple field names can be specified to retrieve an array of values). examples are below, bestie. 🫢

my $value = $line->test();

OR

my $value = $line->get('test');

OR

my @values = $line->get(qw/test test2 test3/);

Setting a fields value ⭐

setting a fields value is simmilar to getting a fields value. there are two ways to set a fields value (as documented in Class::Accessor). firstly you can simply call the field name on the object with the value as the argument, or secondly you can call "set" on the object with a hash of fields and their values to set (this isn't standard in Class::Accessor, i have overloaded the "set" method to allow this). examples are below πŸ’…

$line->test('123');

OR

$line->set( test => '123' );

OR

$line->set(
  test  => '123',
  test2 => '456'
);

Retrieving a line as a string πŸŽ€

to retrieve a line as a string simply call "string" on the object.

my $string = $line->string();

new_line

returns a new line object, this can be useful for to "splice" a line into lines (see example below). you can pass the values of the line as an ARRAY ref or a HASH ref. both slay, pick your fighter ✨

Example 🌈

my $line = $csv->new_line({ userid => 123, domainname => 'splicey.com' });
my @lines = $csv->lines();
splice(@lines, 1, 0, $line);

OR

splice(@{$csv->lines()}, 1, 0, $csv->new_line({ userid => 123, domainname => 'splicey.com' }));

add_line

adds a line to the lines stack. this is mainly useful when the new constructor is used, but can of course be used with any constructor. it will add a new line to the end of the lines stack. you can pass the values of the line as an ARRAY ref or a HASH ref. examples of how to use this are below. πŸ’–

Example πŸ¦‹

$csv->add_line(['house', 100000, 4]);

$csv->add_line({
  item     => 'house',
  cost     => 100000,
  bedrooms => 4
});

πŸ“€ OUTPUT πŸ“€

string

returns the object as a string (CSV file format). your whole CSV, but make it a string ✨

print

calls "print" on string (prints the CSV to STDOUT). straight to your terminal, no filter πŸ”₯


πŸ‘€ SEE ALSO πŸ‘€

Text::CSV_XS, Class::Accessor

go read those too, they're the supporting cast and they ate πŸ’…


πŸ‘‘ AUTHOR πŸ‘‘

David Radunz, <david@boxen.net>


Copyright 2004 by David Radunz

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


okay that's the whole page bestie, you're officially a Class::CSV girlie now 🫢

and one last thing before you go β€” this page is from perl v5.32.1, dated 2021-12-26, filed under CSV(3pm). mwah, bye πŸ’‹πŸŽ€

πŸ“¦ where this page comes from