CSV(3pm)
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::DBIobjects). for this to work properly, the field names provided infieldsneed to correspond to the field names of the objects in the array ref. matchy matchy β¨classdbi_objectsβ depreciated, useobjectsinstead. usingclassdbi_objectswill 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 β¨
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 AND LICENSE π
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
- debian bookworm: libclass-csv-perl 1.03-2.3
- ubuntu jammy: libclass-csv-perl 1.03-2.3
- ubuntu noble: libclass-csv-perl 1.03-2.3
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms