Text::...ncoded(3pm)

๐Ÿ“ฆ
version 0.25 ยท 2 versions
  • 0.25 ยท debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 0.25 ยท ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

๐Ÿ’– Text::CSV::Encoded โ€” the manual page, but make it make sense ๐Ÿ’–

okay bestie, welcome to Text::CSV::Encoded(3pm) from the User Contributed Perl Documentation section. it's giving encoding-aware CSV and honestly? she's iconic. let's get into it ๐ŸŽ€


โœจ NAME โœจ

Text::CSV::Encoded โ€” an encoding aware Text::CSV. no cap, that's the whole vibe. ๐Ÿ’…


๐ŸŒธ VERSION ๐ŸŒธ

version 0.25


๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

here's how you actually use her, literally:

# Here in Perl 5.8 or later
$csv = Text::CSV::Encoded->new ({
    encoding_in  => "iso-8859-1", # the encoding comes into   Perl
    encoding_out => "cp1252",     # the encoding comes out of Perl
});

# parsing CSV is regarded as input
$csv->parse( $line );      # $line is a iso-8859-1 encoded string
@columns = $csv->fields(); # they are unicode data

# combining list is regarded as output
$csv->combine(@columns);   # they are unicode data
$line = $csv->string();    # $line is a cp1252 encoded string

# if you want for returned @columns to be encoded in $encoding
#   or want for combining @columns to be assumed in $encoding
$csv->encoding( $encoding );

# change input/output encodings
$csv->encoding_in('shiftjis')->encoding_out('utf8');
$csv->eol("\n");

open (my $in,  "sjis.csv");
open (my $out, "output.csv");

# change an encoding from shiftjis to utf8

while( my $columns = $csv->getline( $in ) ) {
    $csv->print( $out, $columns );
}

close($in);
close($out);

# simple shortcuts
# (regardless of encoding_in/out and encoding)

$uni_columns = $csv->decode( 'euc-jp', $line );         # euc-jp => unicode
$line        = $csv->encode( 'euc-jp', $uni_columns );  # unicode => euc-jp

# pass check value to coder class
$csv->coder->encode_check_value( Encode::FB_PERLQQ );

๐ŸŒˆ DESCRIPTION ๐ŸŒˆ

this module inherits from Text::CSV and she is aware of input/output encodings. that's it, that's the whole main character moment. โœจ


๐Ÿงš ENCODINGS ๐Ÿงš

the acceptable names of encodings โ€” that's encoding_in, encoding_out and encoding โ€” depend upon its coder class (peep the "CODER CLASS" section). but these names should be based on Encode supported names. go look at Encode::Supported and Encode::Alias. ๐Ÿซถ


๐Ÿ’œ METHODS ๐Ÿ’œ

๐ŸŒŸ new ๐ŸŒŸ

$csv = Text::CSV::Encoded->new();

Text::CSV::Encoded->error_diag unless $csv; # report error message

creates a new Text::CSV::Encoded object. she can take all options of Text::CSV. and obviously, the binary option is always on. ๐Ÿ’…

if Text::CSV::Encoded fails while constructing, you can grab an error message with error_diag. go see "error_diag" in Text::CSV.

the following options are supported by this method, bestie:

  • encoding โ€” the encoding of list data in the below cases:
    • list data returned by fields() after successful parse().
    • list data consumed by combine().
    • list reference returned by getline().
    • list reference taken by print().

see "encoding".

  • encoding_in, encoding_io_in, encoding_to_parse โ€” the encoding for pre-parsing CSV strings. see "encoding_in".
    • encoding_io_in is an alias to encoding_in. if both encoding_in and encoding_io_in are set at the same time, the encoding_in takes precedence.
    • encoding_to_parse is an alias to encoding_in. if both encoding_in and encoding_to_parse are set at the same time, the encoding_in takes precedence.
  • encoding_out, encoding_io_out, encoding_to_combine โ€” the encoding for combined CSV strings. see "encoding_out".
    • encoding_io_out is an alias to encoding_out. if both encoding_out and encoding_io_out are set at the same time, the encoding_out takes precedence.
    • encoding_to_combine is an alias to encoding_out. if both encoding_out and encoding_io_out are set at the same time, the encoding_out takes precedence.
ngl the original literally says encoding_out vs encoding_io_out in that last precedence line and we are NOT fixing it, we preserve. periodt. ๐Ÿ’€
  • coder_class โ€” a name of coder class that really decodes and encodes data. the one doing the actual work. ๐Ÿ”ฅ

๐ŸŒธ encoding_in ๐ŸŒธ

$csv = $csv->encoding_in( $encoding );

the accessor to an encoding for pre-parsing CSV strings. if no encoding is given, she returns the current $encoding, otherwise the object itself.

$encoding = $csv->encoding_in()

in parse or getline, the $csv will assume CSV data as the given encoding. if encoding_in is not specified or is set with a false value (undef), she will assume input CSV strings as Unicode (not UTF-8) when Text::CSV::Encoded::Coder::Encode is used.

$csv->encoding_in( undef );
# assume as Unicode when Text::CSV::Encoded::Coder::Encode is used.

if you pass a list reference that contains multiple encodings to the method, the working are depend upon the coder class. for example, if you use the coder class with Text::CSV::Encoded::Coder::EncodeGuess, it might guess the encoding from the given list. ๐Ÿ”ฎ

$csv->coder_class( 'Text::CSV::Encoded::Coder::EncodeGuess' );
$csv->encoding_in( ['shiftjis', 'euc-jp', 'iso-20022-jp'] );

see "Coder Class" and Text::CSV::Encoded::Coder::EncodeGuess.


๐ŸŒผ encoding_out ๐ŸŒผ

$csv = $csv->encoding_out( $encoding );

the accessor to an encoding for converting combined CSV strings. if no encoding is given, she returns the current $encoding, otherwise the object itself.

$encoding = $csv->encoding_out();

in combine or print, the $csv will return a result string encoded in the given encoding. if encoding_out is not specified or is set with a false value, she will return a result string as Unicode (not UTF-8).

$csv->encoding_out( undef );
# return as Unicode when Text::CSV::Encoded::Coder::Encode is used.
okay listen: you must NOT pass a list reference to encoding_out, unlike encoding_in or encoding. she said what she said. ๐Ÿšซ

๐Ÿ’– encoding ๐Ÿ’–

$csv = $csv->encoding( $encoding );
$encoding = $csv->encoding();

the accessor to an encoding for list data in the below cases:

  • list data returned by fields() after successful parse().
  • list data consumed by combine().
  • list reference returned by getline().
  • list reference taken by print().

in other word, in parse and getline, encoding is an encoding of the returned list. and in combine and print, it is assumed as an encoding for the passing list data.

if encoding is not specified or is set with a false value (undef), the field data will be regarded as Unicode (when Text::CSV::Encoded::Coder::Encode is used).

# ex.) a source code is encoded in euc-jp, and print to stdout in shiftjis.
@fields = ( .... );
$csv->encoding('euc-jp')
    ->encoding_to_combine('shiftjis') # same as encoding_out
    ->combine( @fields ); # from euc-jp to shift_jis

print $csv->string;

$csv->encoding('shiftjis')
    ->encoding_to_parse('shiftjis') # same as encoding_in
    ->parse( $csv->string ); # from shift_jis to shift_jis

print join(", ", $csv->fields );

if you pass a list reference contains multiple encodings to the method, the working are depend upon the coder class. for example, Text::CSV::Encoded::EncodeGuess might guess the encoding from the given list.

$csv->coder_class( 'Text::CSV::Encoded::Coder::EncodeGuess' );
$csv->encoding( ['ascii', 'ucs2'] )->combine( @cols );

see "Coder Class" and Text::CSV::Encoded::Coder::EncodeGuess.


๐Ÿฆ‹ parse/combine/getline/print ๐Ÿฆ‹

$csv->parse( $encoded_string );
@unicode_array = $csv->fields();

$csv->combine( @unicode_array );
$encoded_string = $csv->string;

$unicode_arrayref = $csv->getline( $io );
# get arrayref contains unicode strings
$csv->print( $io, $unicode_arrayref );
# print $io with string encoded in $csv->encoded_in.

$encoded_arrayref = $csv->getline( $io => $encoding )
# directly encoded in $encoding.

here's the relation of encoding_in, encoding_out and encoding, laid out for the girlies:

# CSV string        =>  (getline/parsed)  =>     Perl array
#           assumed as                  encoded in
#                encoding_in                encoding

# Perl array        =>  (print/combined)  =>     CSV string
#           assumed as                  encoded in
#               encoding                    encoding_out

if you want to treat Perl array data as Unicode in Perl5.8 and later, don't specify encoding (or set undef into encoding). easy. ๐Ÿ’…


๐ŸŽ€ decode ๐ŸŽ€

$arrayref = $csv->decode( $encoding, $encoded_string );

$arrayref = $csv->decode( $string );

a short cut method to convert CSV to Perl. without $encoding, $string is assumed as a Unicode.

the returned value status is depend upon its coder class. with Text::CSV::Encoded::Coder::Encode, $arrayref contains Unicode strings.


โญ encode โญ

$encoded_string = $csv->encode( $encoding, $arrayref );

$string = $csv->encode( $arrayref );

a short cut method to convert Perl to CSV. with Text::CSV::Encoded::Coder::Encode, $arrayref is assumed to contain Unicode strings.

without $encoding, return as is. ๐Ÿซถ


๐Ÿ“ coder_class ๐Ÿ“

$csv = $csv->coder_class( $classname );
$classname = $csv->coder_class();

returns the coder class name. see "CODER CLASS".


๐Ÿ‘‘ coder ๐Ÿ‘‘

$coder = $csv->coder();

returns a coder object. the little helper doing the encoding heavy lifting. โœจ


๐Ÿ’€ automtic_UTF8 ๐Ÿ’€

in Text::CSV_XS version 0.99 and Text::CSV_PP version 1.30 or later, they return UNICODE stinrgs in case of parsing utf8 encoded text. backend module has that feature, so automtic_UTF8 returns true. (this method is for internal code.)

yep, the method name is spelled automtic_UTF8 and the prose says "stinrgs". we do not edit the ancestors. we honor them. ๐Ÿ™ˆ

okay bestie ๐Ÿ’– we're picking up right where we left off, and now we're getting into the CODER CLASS of it all, which is honestly where the โœจmagicโœจ happens.

๐ŸŽ€ CODER CLASS ๐ŸŽ€

So here's the tea: Text::CSV::Encoded doesn't do the encoding converting itself โ€” it delegates that whole process to another module. Iconic delegation, no notes. ๐Ÿซถ

Ever since version 5.8, Perl comes standard with the Encode module, so the default coder module Text::CSV::Encoded::Coder::Encode also uses it. In this case, you genuinely don't have to take care of it. It's handled. Periodt. ๐Ÿ’…

But on older Perl, the default is Text::CSV::Encoded::Coder::Base. And bestie... it does nothing. ๐Ÿ˜ญ So you have to make a coder module yourself using your favorite converting module โ€” for example Unicode::String or Jcode and so on. You got this, fr fr.

Please check out Text::CSV::Encoded::Coder::Base and Text::CSV::Encoded::Coder::Encode to make such a module. They're your blueprint, your blueprint-bestie. ๐Ÿฆ‹

And when you're calling Text::CSV::Encoded, you can set another coder module with coder_class:

  use Text::CSV::Encoded coder_class => 'YourCoder';

This will call the YourCoder module in runtime. slay โœจ


๐Ÿ”ค Use Encode module

Perl 5.8 or later, Text::CSV::Encoded uses Text::CSV::Encoded::Coder::Encode as its backend engine. You can set encoding_in, encoding_out and encoding with Encode supported encodings. Go peek at Encode::Supported and Encode::Alias for the full menu. ๐Ÿ“œ

Without encoding (or set undef), parse / getline / getline_hr return list data whose entries are Unicode strings. On the contrary (yes, we're being fancy), combine / print take data as a Unicode string list. ๐Ÿ’œ

Now about the extra methods decode and encode. decode returns a Unicode string list, and encode takes a Unicode string list. But if no $encoding is passed to encode, it returns a non-Unicode CSV string for non-Unicode list data. the way that just works ๐Ÿ˜Œ


๐Ÿ”ฎ Use Encode::Guess module

If you don't know definitely the input CSV data encoding (for parse/getline), then Text::CSV::Encoded::Coder::EncodeGuess may be useful to you. ๐Ÿ‘‘ It inherits from Text::CSV::Encoded::Coder::Encode, so you can treat methods and attributes the same as Text::CSV::Encoded::Coder::Encode. And it provides a guessing function with Encode::Guess. Detective mode: activated. ๐Ÿ”

When it's the backend coder class, encoding_in and encoding can take an encoding list reference, and then it might guess the encoding from the given list.

    $csv->encoding_in( ['shiftjis', 'euc-jp'] )->parse( $sjis_or_eucjp_encoded_csv_string );
โš ๏ธ It is important to remember the guessing feature is not always successful. Do not come for me when it guesses wrong, bestie. It's doing its best. ๐Ÿ™ˆ

Or, the method can be applied to encoding. For example, you want to convert data from Microsoft Excel to CSV. Very relatable scenario, honestly.

    use Text::CSV::Encoded  coder_class => 'Text::CSV::Encoded::Coder::EncodeGuess';
    use Spreadsheet::ParseExcel;

    my $csv = Text::CSV::Encoded->new( eol => "\n" );
    $csv->encoding( ['ucs2', 'ascii'] ); # guessing ucs2 or ascii?
    $csv->encoding_out('shiftjis'); # print in shift_jis

    my $excel = Spreadsheet::ParseExcel::Workbook->Parse( $file );
    my $sheet = $excel->{Worksheet}->[0];

    for my $row ( $sheet->{MinRow} .. $sheet->{MaxRow} ) {
        my @fields;
        for my $col ( $sheet->{MinCol} ..  $sheet->{MaxCol} ) {
            my $cell = $sheet->{Cells}[$row][$col];
            push @fields, $cell->{Val};
        }
        $csv->print( \@fields );
    }

In this case, guessing for list data. After combining, you may have a need to clear encoding. Again remember that the feature is not always successful. I'm saying it twice because it matters, okay? ๐Ÿซ 

In addition, Microsoft Excel data converting is a careful thing. See to "CAVEATS" in Text::CSV_XS. Don't say I didn't warn you. ๐Ÿ’€


๐Ÿงš Use XXX module

Someone might make a new coder module in older version Perl... and honestly, good for them. There is an example with Jcode in the Text::CSV::Encoded::Coder::Base document. Go look, it's giving documentation. ๐Ÿ“–


๐Ÿ“ TODO

The maintainer's own to-do list, and we respect the honesty:

  • More sophisticated tests - Welcome! ๐ŸŽ‰ (yes, you specifically, come through)
  • Speed ๐ŸŽ๏ธ

๐Ÿ‘€ SEE ALSO

Your reading list, bestie โ€” go forth and click around:

  • Text::CSV
  • Text::CSV_XS
  • Encode
  • Encode::Guess
  • utf8
  • Text::CSV::Encoded::Coder::Base
  • Text::CSV::Encoded::Coder::Encode
  • Text::CSV::Encoded::Coder::EncodeGuess

๐Ÿ’– AUTHOR

Makamaka Hannyaharamitu, <makamaka[at]cpan.org>

The basic idea for this module and suggestions were given by H.Merijn Brand. He and Juerd advised me many points about documents and sources. shoutout to the whole committee, no cap ๐Ÿซถ


Copyright 2008-2013 by Makamaka Hannyaharamitu

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


and that's a wrap on the whole page, bestie!! ๐ŸŒˆ๐ŸŒธ this was perl v5.36.0, dated 2022-11-19, and the page itself is Text::...ncoded(3pm). go forth, encode responsibly, and remember: the guessing is never guaranteed ๐Ÿ’…โœจ bye bestie!! ๐Ÿฆ‹๐ŸŽ€

๐Ÿ“ฆ where this page comes from