Text::...Parser(3pm)

πŸŽ€ NAME πŸŽ€

okay bestie, welcome to the Text::...Parser(3pm) page from User Contributed Perl Documentation! πŸ’–

Text::RecordParser β€” literally reads record-oriented files. That's the whole vibe. πŸ¦‹


✨ SYNOPSIS ✨

here's the group-chat tutorial, fr fr β€” copy-paste these and you're golden:

use Text::RecordParser;

# use default record (\n) and field (,) separators
my $p = Text::RecordParser->new( $file );

# or be explicit
my $p = Text::RecordParser->new({
    filename        => $file,
    field_separator => "\t",
});

$p->filename('foo.csv');

# Split records on two newlines
$p->record_separator("\n\n");

# Split fields on tabs
$p->field_separator("\t");

# Skip lines beginning with hashes
$p->comment( qr/^#/ );

# Trim whitespace
$p->trim(1);

# Use the fields in the first line as column names
$p->bind_header;

# Get a list of the header fields (in order)
my @columns = $p->field_list;

# Extract a particular field from the next row
my ( $name, $age ) = $p->extract( qw[name age] );

# Return all the fields from the next row
my @fields = $p->fetchrow_array;

# Define a field alias
$p->set_field_alias( name => 'handle' );

# Return all the fields from the next row as a hashref
my $record = $p->fetchrow_hashref;
print $record->{'name'};
# or
print $record->{'handle'};

# Return the record as an object with fields as accessors
my $object = $p->fetchrow_object;
print $object->name; # or $object->handle;

# Get all data as arrayref of arrayrefs
my $data = $p->fetchall_arrayref;

# Get all data as arrayref of hashrefs
my $data = $p->fetchall_arrayref( { Columns => {} } );

# Get all data as hashref of hashrefs
my $data = $p->fetchall_hashref('name');

🌸 DESCRIPTION 🌸

okay so this module is for reading record-oriented data in a delimited text file. πŸ’… The most common example has records separated by newlines and fields separated by commas or tabs, but this module aims to provide a consistent interface for handling sequential records in a file however they may be delimited. ✨

Typically this data lists the fields in the first line of the file, in which case you should call bind_header to bind the field name (or not, and it will be called implicitly). πŸ™ˆ If the first line contains data, you can still bind your own field names via bind_fields. πŸŽ€ Either way, you can then use many methods to get at the data as arrays or hashes. πŸ”₯

✨ METHODS ✨


πŸ’… new

Okay bestie, this is the object constructor, the moment we all met πŸ’– It takes a hash (or a hashref, either one, she's flexible) of arguments. And here's the cute part: every single argument can also be set later through the method of the same name. So whatever you pass in, there's a matching method waiting for you.

  • filename β€” the path to the file being read. If you pass the filename and you do not pass the fh, then she'll open a filehandle on that file for you and set fh accordingly. Self-sufficient queen ✨
  • comment β€” a compiled regular expression identifying comment lines that should be skipped. Bye bye, comments πŸ‘‹
  • data β€” the data to read.
  • fh β€” the filehandle of the file to read.
  • field_separator | fs β€” the field separator (default is comma). The classic.
  • record_separator | rs β€” the record separator (default is newline).
  • field_filter β€” a callback applied to all the fields as they are read.
  • header_filter β€” a callback applied to the column names.
  • trim β€” boolean to enable trimming of leading and trailing whitespace from fields (super useful if you're splitting on whitespace only).

See the methods for each argument name for more info, because yes, they all get their own lil spotlight below 🌸

Also! Alternately, if you supply a single argument to new, it will be treated as the filename argument. One-arg convenience, we love to see it 🫢


πŸŽ€ bind_fields

$p->bind_fields( qw[ name rank serial_number ] );

Takes an array of field names and memorizes the field positions for later use. So if your input file has no header line but you still wanna grab fields by name β€” or even if you do wanna call bind_header and then hand over your own field names β€” just pass in the array of field names you want to use. Your rules, your names πŸ‘‘

Pass in an empty array reference to unset:

$p->bind_field( [] ); # unsets fields

πŸ¦‹ bind_header

$p->bind_header;
my $name = $p->extract('name');

Takes the fields from the next row under the cursor and assigns the field names to the values. Usually you'd call this immediately after opening the file, so the first row's field names get bound. First row = header row, it's giving efficiency πŸ’…


🌸 comment

$p->comment( qr/^#/ );  # Perl-style comments
$p->comment( qr/^--/ ); # SQL-style comments

Takes a regex to apply to a record to see if it looks like a comment to skip. If it matches, she's not even reading it, periodt.


πŸ“ data

$p->data( $string );
$p->data( \$string );
$p->data( @lines );
$p->data( [$line1, $line2, $line3] );
$p->data( IO::File->new('<data') );

Allows a scalar, scalar reference, glob, array, or array reference as the thing to read instead of a file handle. So many options, so many vibes 🌈

Heads up bestie: it's not advised to pass a filehandle to data, because it will read the entire contents of the file rather than one line at a time if you set it via fh. Like, the whole thing at once. Not the move 😭

πŸ‘‘

my ( $foo, $bar, $baz ) = $p->extract( qw[ foo bar baz ] );

Extracts a list of fields out of the last row read. The field names must correspond to the field names bound either via bind_fields or bind_header. No random names, she needs to already know them πŸ’–


πŸ’œ fetchrow_array

my @values = $p->fetchrow_array;

Reads a row from the file and returns an array or array reference of the fields. Simple, clean, iconic.


✨ fetchrow_hashref

my $record = $p->fetchrow_hashref;
print "Name = ", $record->{'name'}, "\n";

Reads a line of the file and returns it as a hash reference. The keys of the hashref are the field names bound via bind_fields or bind_header. And if you did not bind fields before calling this method? Don't stress, the bind_header method will be implicitly called for you. She's got you 🫢


πŸ”₯ fetchrow_object

while ( my $object = $p->fetchrow_object ) {
    my $id   = $object->id;
    my $name = $object->naem; # <-- this will throw a runtime error
}

This will return the next data record as a Text::RecordParser::Object object that has read-only accessor methods of the field names and any aliases. This lets you enforce field names, which further helps ensure your code is actually reading the input file correctly. Like, if you're using the fetchrow_hashref method to read each line, you might misspell the hash key and introduce a bug in your code β€” sneaky little typo, big consequences πŸ’€ With this method, Perl will throw an error if you attempt to read a field that's not defined in the file's headers. Additionally, any defined field aliases will be created as additional accessor methods. Guard rails, but make it glamorous πŸŽ€


🌟 fetchall_arrayref

my $records = $p->fetchall_arrayref;
for my $record ( @$records ) {
    print "Name = ", $record->[0], "\n";
}

my $records = $p->fetchall_arrayref( { Columns => {} } );
for my $record ( @$records ) {
    print "Name = ", $record->{'name'}, "\n";
}

Like DBI's fetchall_arrayref, returns an arrayref of arrayrefs. Also accepts an optional { Columns => {} } argument to return an arrayref of hashrefs instead. Both flavors available, pick your poison bestie πŸ’…


πŸ’– fetchall_hashref

my $records = $p->fetchall_hashref('id');
for my $id ( keys %$records ) {
    my $record = $records->{ $id };
    print "Name = ", $record->{'name'}, "\n";
}

Like DBI's fetchall_hashref, this returns a hash reference of hash references. The keys of the top-level hashref are the field values of the field argument you supply. And the field name you supply can be a field created by a field_compute β€” yes, even your homemade computed fields can be keys. Main character energy πŸ‘‘


🧚 fh

open my $fh, '<', $file or die $!;
$p->fh( $fh );

Gets or sets the filehandle of the file being read. That's it, that's the method πŸ¦‹


🌸 field_compute

A callback applied to the fields identified by position (or field name if bind_fields or bind_header was called).

The callback will be passed two arguments:

  1. The current field
  2. A reference to all the other fields, either as an array or hash reference, depending on the method which you called.

If data looks like this:

parent    children
Mike      Greg,Peter,Bobby
Carol     Marcia,Jane,Cindy

You could split the children field into an array reference with the values like so:

$p->field_compute( 'children', sub { [ split /,/, shift() ] } );

The field position or name doesn't actually have to exist, which means you could create new, computed fields on-the-fly. E.g., if your data looks like this:

    1,3,5
    32,4,1
    9,5,4

You could write a field_compute like this:

$p->field_compute( 3,
    sub {
        my ( $cur, $others ) = @_;
        my $sum;
        $sum += $_ for @$others;
        return $sum;
    }
);

Field 3 will be created as the sum of the other fields. This allows you to further write:

my $data = $p->fetchall_arrayref;
for my $rec ( @$data ) {
    print "$rec->[0] + $rec->[1] + $rec->[2] = $rec->[3]\n";
}

Prints:

1 + 3 + 5 = 9
32 + 4 + 1 = 37
9 + 5 + 4 = 18

Math? In my parser? It's more likely than you think πŸ˜­πŸ’–


πŸŽ€ field_filter

$p->field_filter( sub { $_ = shift; uc(lc($_)) } );

A callback which is applied to each field. The callback will be passed the current value of the field, and whatever is passed back becomes the new value of the field. The example above capitalizes field values. To unset the filter, pass in the empty string. Glow-up for your data ✨


🌈 field_list

$p->bind_fields( qw[ foo bar baz ] );
my @fields = $p->field_list;
print join ', ', @fields; # prints "foo, bar, baz"

Returns the fields bound via bind_fields (or bind_header). Just a cute lil list of your field names 🫢


πŸ’… field_positions

my %positions = $p->field_positions;

Returns a hash of the fields and their positions bound via bind_fields (or bind_header). Mostly for internal use β€” so like, she's doing behind-the-scenes work, but you can peek if you want πŸ™ˆ


⭐ field_separator

$p->field_separator("\t");     # splits fields on tabs
$p->field_separator('::');     # splits fields on double colons
$p->field_separator(qr/\s+/);  # splits fields on whitespace
my $sep = $p->field_separator; # returns the current separator

Gets and sets the token to use as the field delimiter. Regular expressions can be specified using qr//. If not specified, it will take a guess based on the filename extension (comma for .txt, .dat, or .csv; tab for .tab). The default is a comma. She's intuitive like that πŸ’…


πŸ¦‹ filename

$p->filename('/path/to/file.dat');

Gets or sets the complete path to the file to be read. And if a file is already opened? Then the handle on it will be closed and a new one opened on the new file. Out with the old, in with the new πŸ‘‘


πŸ’œ get_field_aliases

my @aliases = $p->get_field_aliases('name');

Allows you to define alternate names for fields, e.g., sometimes your input file calls city "town" or "township," sometimes a file uses "Moniker" instead of "name." Your data has a lot of nicknames and honestly? Respect 🌸


πŸ“ header_filter

$p->header_filter( sub { $_ = shift; s/\s+/_/g; lc $_ } );

A callback applied to column header names. The callback will be passed the current value of the header, and whatever is returned becomes the new value of the header. The example above collapses spaces into a single underscore and lowercases the letters. To unset a filter, pass in the empty string. Clean header era ✨


πŸ’– record_separator

$p->record_separator("\n//\n");
$p->field_separator("\n");

Gets and sets the token to use as the record separator. The default is a newline (\n).

The above example would read a file that looks like this:

field1
field2
field3
//
data1
data2
data3
//

Custom separators, custom chaos, we love her 🌈


🧚 set_field_alias

$p->set_field_alias({
    name => 'Moniker,handle',        # comma-separated string
    city => [ qw( town township ) ], # or anonymous arrayref
});

Allows you to define alternate names for fields, e.g., sometimes your input file calls city "town" or "township," sometimes a file uses "Moniker" instead of "name." Same energy as get_field_aliases, but you're the one setting them πŸ’…


πŸŽ€ trim

my $trim_value = $p->trim(1);

Provide a "true" argument to remove leading and trailing whitespace from fields. Use a "false" argument to disable. So fresh, so clean 🫧


πŸ‘‘ AUTHOR πŸ‘‘

Ken Youens-Clark <kclark@cpan.org>


πŸ”— SOURCE πŸ”—

http://github.com/kyclark/text-recordparser


πŸ’– CREDITS πŸ’–

Thanks to the following:

  • Benjamin Tilly

For Text::xSV, the inspirado for this module

  • Tim Bunce et al.

For DBI, from which many of the methods were shamelessly stolen

  • Tom Aldcroft

For contributing code to make it easy to parse whitespace-delimited data

  • Liya Ren

For catching the column-ordering error when parsing with no-headers

  • Sharon Wei

For catching bug in extract that sets up infinite loops

  • Lars Thegler

For bug report on missing script_files arg in Build.PL

Shoutout to the whole squad, this module would not be here without y'all 🫢✨


πŸ™ˆ BUGS πŸ™ˆ

None known. Please use http://rt.cpan.org/ for reporting bugs.

No known bugs, bestie β€” she's flawless (allegedly) πŸ’… But if you do find one, rt.cpan.org is the place to spill.

okay bestie, legal time, but make it cute πŸ’–

Copyright (C) 2006-10 Ken Youens-Clark. All rights reserved. β€” yes, that's Ken Youens-Clark, from way back in 2006 through 2010, and the "all rights reserved" is doing its little legal strut, we love that for him πŸ‘‘


🫢 the part where you can actually use it

this program is free software, fr fr. you can:

  • redistribute it
  • and/or modify it

under the terms of the GNU General Public License as published by the Free Software Foundation, and the version in question is version 2. periodt. that's the vibe πŸ’…

lowkey important: it's version 2 specifically, not "2 or later", not "whatever the newest one is". version 2. that's the whole deal. no cap.

😭 the part every license has to yell about (in all caps, iconic behaviour)

this program is distributed in the hope that it will be useful, but:

WITHOUT ANY WARRANTY β€” like, none. zero. nada πŸ™ˆ

and specifically, no warranty of MERCHANTABILITY and no warranty of FITNESS FOR A PARTICULAR PURPOSE. the all-caps is not me being dramatic, that's literally how it's written and honestly it's giving main character energy πŸŽ€

if you want the details, the GNU General Public License has all of them β€” go read it, iykyk πŸ“–βœ¨


🌈 and that's the whole page!!

that's it, bestie, we made it to the end of Text::...Parser(3pm) πŸ¦‹ you now know the methods, the author, the source, the credits, the bugs, and the extremely legally-binding vibes. go parse something and slay ✨

this little walkthrough came from perl v5.36.0, dated 2022-10-14, and it's the documentation for Text::...Parser(3pm) πŸ’œ take care of her, she's been around since 2006 πŸ‘‘πŸ’–

πŸ“¦ where this page comes from