home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / CSV_XS.pm < prev    next >
Encoding:
Perl POD Document  |  2002-06-14  |  16.4 KB  |  587 lines

  1. package Text::CSV_XS;
  2.  
  3. # Copyright (c) 1998 Jochen Wiedmann. All rights reserved.
  4. #
  5. # Portions Copyright (c) 1997 Alan Citterman. All rights reserved.
  6. #
  7. # This program is free software; you can redistribute it and/or
  8. # modify it under the same terms as Perl itself.
  9.  
  10. ################################################################################
  11. # HISTORY
  12. #
  13. # Written by:
  14. #    Jochen Wiedmann <joe@ispsoft.de>
  15. #
  16. # Based on Text::CSV by:
  17. #    Alan Citterman <alan@mfgrtl.com>
  18. #
  19. ############################################################################
  20.  
  21. require 5.004;
  22. use strict;
  23.  
  24.  
  25. use DynaLoader ();
  26.  
  27. use vars qw($VERSION @ISA);
  28.  
  29. $VERSION =     '0.23';
  30. @ISA =         qw(DynaLoader);
  31.  
  32.  
  33. sub PV () { 0 }
  34. sub IV () { 1 }
  35. sub NV () { 2 }
  36.  
  37.  
  38. ############################################################################
  39. #
  40. # version
  41. #
  42. #    class/object method expecting no arguments and returning the version
  43. #    number of Text::CSV.  there are no side-effects.
  44. #
  45. ############################################################################
  46. sub version {
  47.   return $VERSION;
  48. }
  49.  
  50.  
  51. ############################################################################
  52. #
  53. # new
  54. #
  55. #    class/object method expecting no arguments and returning a reference to
  56. #    a newly created Text::CSV object.
  57. #
  58. ############################################################################
  59.  
  60. sub new ($;$) {
  61.     my $proto = shift;  my $attr = shift || {};
  62.     my $class = ref($proto) || $proto;
  63.     my $self = { 'quote_char' => '"',
  64.          'escape_char' => '"',
  65.          'sep_char' => ',',
  66.          'eol' => '',
  67.          %$attr };
  68.     bless $self, $class;
  69.     if (exists($self->{'types'})) {
  70.     $self->types($self->{'types'});
  71.     }
  72.     $self;
  73. }
  74.  
  75.  
  76. ############################################################################
  77. #
  78. # status
  79. #
  80. #    object method returning the success or failure of the most recent
  81. #    combine() or parse().  there are no side-effects.
  82. ############################################################################
  83.  
  84. sub status ($) {
  85.   my $self = shift;
  86.   return $self->{'_STATUS'};
  87. }
  88.  
  89.  
  90. ############################################################################
  91. #
  92. # error_input
  93. #
  94. #    object method returning the first invalid argument to the most recent
  95. #    combine() or parse().  there are no side-effects.
  96. ############################################################################
  97.  
  98. sub error_input ($) {
  99.   my $self = shift;
  100.   return $self->{'_ERROR_INPUT'};
  101. }
  102.  
  103.  
  104. ############################################################################
  105. #
  106. # string
  107. #
  108. #    object method returning the result of the most recent combine() or the
  109. #    input to the most recent parse(), whichever is more recent.  there are
  110. #    no side-effects.
  111. #
  112. ############################################################################
  113.  
  114. sub string ($) {
  115.   my $self = shift;
  116.   return $self->{'_STRING'};
  117. }
  118.  
  119.  
  120. ############################################################################
  121. # fields
  122. #
  123. #    object method returning the result of the most recent parse() or the
  124. #    input to the most recent combine(), whichever is more recent.  there
  125. #    are no side-effects.
  126. #
  127. ############################################################################
  128.  
  129. sub fields ($) {
  130.   my $self = shift;
  131.   if (ref($self->{'_FIELDS'})) {
  132.     return @{$self->{'_FIELDS'}};
  133.   }
  134.   return undef;
  135. }
  136.  
  137.  
  138. ############################################################################
  139. #
  140. # combine
  141. #
  142. #    object method returning success or failure.  the given arguments are
  143. #    combined into a single comma-separated value.  failure can be the
  144. #    result of no arguments or an argument containing an invalid character.
  145. #    side-effects include:
  146. #      setting status()
  147. #      setting fields()
  148. #      setting string()
  149. #      setting error_input()
  150. #
  151. ############################################################################
  152.  
  153. sub combine ($@) {
  154.   my $self = shift;
  155.   my @part = @_;
  156.   my($str) = '';
  157.   my($ref) = \$str;
  158.   $self->{'_FIELDS'} = \@part;
  159.   $self->{'_ERROR_INPUT'} = undef;
  160.   $self->{'_STATUS'} =
  161.       (@part > 0)  &&  $self->Encode(\$str, \@part, 0, $self->{'eol'});
  162.   $self->{'_STRING'} = $str;
  163.   $self->{'_STATUS'};
  164. }
  165.  
  166.  
  167. ############################################################################
  168. #
  169. # parse
  170. #
  171. #    object method returning success or failure.  the given argument is
  172. #    expected to be a valid comma-separated value.  failure can be the
  173. #    result of no arguments or an argument containing an invalid sequence
  174. #    of characters. side-effects include:
  175. #      setting status()
  176. #      setting fields()
  177. #      setting string()
  178. #      setting error_input()
  179. #
  180. #############################################################################
  181.  
  182. sub parse ($$) {
  183.   my($self, $str) = @_;
  184.   my($fields) = [];
  185.   $self->{'_STRING'} = $self->{'ERROR_INPUT'} = $str;
  186.   $self->{'_STATUS'} = 0;
  187.   $self->{'_FIELDS'} = undef;
  188.   if (defined($str)  &&  $self->Decode($str, $fields, 0)) {
  189.       $self->{'_FIELDS'} = $fields;
  190.       $self->{'_STATUS'} = 1;
  191.   }
  192.   return ($self->{'_STATUS'});
  193. }
  194.  
  195.  
  196. ############################################################################
  197. #
  198. #    Name:    print (Instance method)
  199. #
  200. #    Purpose: Similar to combine, but the fields are encoded to an
  201. #             IO stream or something similar. To be precise: An
  202. #             object supporting a "print" method.
  203. #
  204. #    Inputs:  $self   - Instance
  205. #             $io     - IO handle or similar object
  206. #             $fields - Array ref to array of fields
  207. #
  208. #    Returns: TRUE for success, FALSE otherwise. In the latter case
  209. #             you may look at $self->error_input() or check the IO
  210. #             object for errors.
  211. #
  212. ############################################################################
  213.  
  214. # sub print ($$$) {
  215. #     my($self, $io, $fields) = @_;
  216. #     $self->{'_ERROR_INPUT'} = undef;
  217. #     $self->{'_STRING'} = undef;
  218. #     $self->{'_FIELDS'} = $fields;
  219. #     $self->{'_STATUS'} = $self->Encode($io, $fields, 1, $self->{'eol'});
  220. # }
  221.  
  222.  
  223. ############################################################################
  224. #
  225. #    Name:    getline (Instance method)
  226. #
  227. #    Purpose: Similar to parse, but the fields are decoded from an
  228. #             IO stream or something similar. To be precise: An
  229. #             object supporting a "getline" method.
  230. #
  231. #             Note that it may happen that multiple lines are read,
  232. #             if the fields contain line feeds and we are in binary
  233. #             mode. For example, MS Excel creates such files!
  234. #
  235. #    Inputs:  $self   - Instance
  236. #             $io     - IO handle or similar object
  237. #
  238. #    Returns: Array ref of fields for success, undef otherwise.
  239. #             In the latter case you may look at $self->error_input()
  240. #             or check the IO object for errors.
  241. #
  242. ############################################################################
  243.  
  244. # sub getline ($$) {
  245. #     my($self, $io) = @_;
  246. #     my($fields) = [];
  247. #     $self->{'_ERROR_INPUT'} = undef;
  248. #     $self->{'_STRING'} = undef;
  249. #     $self->{'_FIELDS'} = $fields;
  250. #     if ($self->{'_STATUS'} = $self->Decode($io, $fields, 1)) {
  251. #     return $fields;
  252. #     }
  253. #     return undef;
  254. # }
  255.  
  256.  
  257. bootstrap Text::CSV_XS $VERSION;
  258.  
  259. sub types {
  260.     my $self = shift;
  261.     if (@_) {
  262.     if (my $types = shift) {
  263.         $self->{'_types'} = join("", map{ chr($_) } @$types);
  264.         $self->{'types'} = $types;
  265.     } else {
  266.         delete $self->{'types'};
  267.         delete $self->{'_types'};
  268.         undef;
  269.     }
  270.     } else {
  271.     $self->{'types'};
  272.     }
  273. }
  274.  
  275. 1;
  276.  
  277. __END__
  278.  
  279. =head1 NAME
  280.  
  281. Text::CSV_XS - comma-separated values manipulation routines
  282.  
  283.  
  284. =head1 SYNOPSIS
  285.  
  286.  use Text::CSV_XS;
  287.  
  288.  $csv = Text::CSV_XS->new();           # create a new object
  289.  $csv = Text::CSV_XS->new(\%attr);     # create a new object
  290.  
  291.  $status = $csv->combine(@columns);    # combine columns into a string
  292.  $line = $csv->string();               # get the combined string
  293.  
  294.  $status = $csv->parse($line);         # parse a CSV string into fields
  295.  @columns = $csv->fields();            # get the parsed fields
  296.  
  297.  $status = $csv->status();             # get the most recent status
  298.  $bad_argument = $csv->error_input();  # get the most recent bad argument
  299.  
  300.  $status = $csv->print($io, $columns); # Write an array of fields immediately
  301.                                        # to a file $io
  302.  
  303.  $columns = $csv->getline($io);        # Read a line from file $io, parse it
  304.                                        # and return an array ref of fields
  305.  
  306.  $csv->types(\@t_array);               # Set column types
  307.  
  308.  
  309. =head1 DESCRIPTION
  310.  
  311. Text::CSV_XS provides facilities for the composition and decomposition of
  312. comma-separated values.  An instance of the Text::CSV_XS class can combine
  313. fields into a CSV string and parse a CSV string into fields.
  314.  
  315.  
  316. =head1 FUNCTIONS
  317.  
  318. =over 4
  319.  
  320. =item version()
  321.  
  322. (Class method) Returns the current module version.
  323.  
  324. =item new(\%attr)
  325.  
  326. (Class method) Returns a new instance of Text::CSV_XS. The objects
  327. attributes are described by the (optional) hash ref C<\%attr>.
  328. Currently the following attributes are available:
  329.  
  330. =over 8
  331.  
  332. =item quote_char
  333.  
  334. The char used for quoting fields containing blanks, by default the
  335. double quote character (C<">). A value of undef suppresses
  336. quote chars. (For simple cases only).
  337.  
  338. =item eol
  339.  
  340. An end-of-line string to add to rows, usually C<undef> (nothing,
  341. default), C<"\012"> (Line Feed) or C<"\015\012"> (Carriage Return,
  342. Line Feed)
  343.  
  344. =item escape_char
  345.  
  346. The char used for escaping certain characters inside quoted fields,
  347. by default the same character. (C<">)
  348.  
  349. =item sep_char
  350.  
  351. The char used for separating fields, by default a comme. (C<,>)
  352.  
  353. =item binary
  354.  
  355. If this attribute is TRUE, you may use binary characters in quoted fields,
  356. including line feeds, carriage returns and NUL bytes. (The latter must
  357. be escaped as C<"0>.) By default this feature is off.
  358.  
  359. =item types
  360.  
  361. A set of column types; this attribute is immediately passed to the
  362. I<types> method below. You must not set this attribute otherwise,
  363. except for using the I<types> method. For details see the description
  364. of the I<types> method below.
  365.  
  366. =item always_quote
  367.  
  368. By default the generated fields are quoted only, if they need to, for
  369. example, if they contain the separator. If you set this attribute to
  370. a TRUE value, then all fields will be quoted. This is typically easier
  371. to handle in external applications. (Poor creatures who aren't using
  372. Text::CSV_XS. :-)
  373.  
  374. =back
  375.  
  376. To sum it up,
  377.  
  378.  $csv = Text::CSV_XS->new();
  379.  
  380. is equivalent to
  381.  
  382.  $csv = Text::CSV_XS->new({
  383.      'quote_char'  => '"',
  384.      'escape_char' => '"',
  385.      'sep_char'    => ',',
  386.      'binary'      => 0
  387.  });
  388.  
  389. =item combine
  390.  
  391.  $status = $csv->combine(@columns);
  392.  
  393. This object function constructs a CSV string from the arguments, returning
  394. success or failure.  Failure can result from lack of arguments or an argument
  395. containing an invalid character.  Upon success, C<string()> can be called to
  396. retrieve the resultant CSV string.  Upon failure, the value returned by
  397. C<string()> is undefined and C<error_input()> can be called to retrieve an
  398. invalid argument.
  399.  
  400. =item print
  401.  
  402.  $status = $csv->print($io, $columns);
  403.  
  404. Similar to combine, but it expects an array ref as input (not an array!)
  405. and the resulting string is not really created, but immediately written
  406. to the I<$io> object, typically an IO handle or any other object that
  407. offers a I<print> method. Note, this implies that the following is wrong:
  408.  
  409.  open(FILE, ">whatever");
  410.  $status = $csv->print(\*FILE, $columns);
  411.  
  412. The glob C<\*FILE> is not an object, thus it doesn't have a print
  413. method. The solution is to use an IO::File object or to hide the
  414. glob behind an IO::Wrap object. See L<IO::File(3)> and L<IO::Wrap(3)>
  415. for details.
  416.  
  417. For performance reasons the print method doesn't create a result string.
  418. In particular the I<$csv-E<gt>string()>, I<$csv-E<gt>status()>,
  419. I<$csv->fields()> and I<$csv-E<gt>error_input()> methods are meaningless
  420. after executing this method.
  421.  
  422. =item string
  423.  
  424.  $line = $csv->string();
  425.  
  426. This object function returns the input to C<parse()> or the resultant CSV
  427. string of C<combine()>, whichever was called more recently.
  428.  
  429. =item parse
  430.  
  431.  $status = $csv->parse($line);
  432.  
  433. This object function decomposes a CSV string into fields, returning
  434. success or failure.  Failure can result from a lack of argument or the
  435. given CSV string is improperly formatted.  Upon success, C<fields()> can
  436. be called to retrieve the decomposed fields .  Upon failure, the value
  437. returned by C<fields()> is undefined and C<error_input()> can be called
  438. to retrieve the invalid argument.
  439.  
  440. You may use the I<types()> method for setting column types. See the
  441. description below.
  442.  
  443.  
  444. =item getline
  445.  
  446.  $columns = $csv->getline($io);
  447.  
  448. This is the counterpart to print, like parse is the counterpart to
  449. combine: It reads a row from the IO object $io using $io->getline()
  450. and parses this row into an array ref. This array ref is returned
  451. by the function or undef for failure.
  452.  
  453. The I<$csv-E<gt>string()>, I<$csv-E<gt>fields()> and I<$csv-E<gt>status()>
  454. methods are meaningless, again.
  455.  
  456. =item types
  457.  
  458.  $csv->types(\@tref);
  459.  
  460. This method is used to force that columns are of a given type. For
  461. example, if you have an integer column, two double columns and a
  462. string column, then you might do a
  463.  
  464.  $csv->types([Text::CSV_XS::IV(),
  465.               Text::CSV_XS::NV(),
  466.               Text::CSV_XS::NV(),
  467.               Text::CSV_XS::PV()]);
  468.  
  469. Column types are used only for decoding columns, in other words
  470. by the I<parse()> and I<getline()> methods.
  471.  
  472. You can unset column types by doing a
  473.  
  474.  $csv->types(undef);
  475.  
  476. or fetch the current type settings with
  477.  
  478.  $types = $csv->types();
  479.  
  480. =item fields
  481.  
  482.  @columns = $csv->fields();
  483.  
  484. This object function returns the input to C<combine()> or the resultant
  485. decomposed fields of C<parse()>, whichever was called more recently.
  486.  
  487. =item status
  488.  
  489.  $status = $csv->status();
  490.  
  491. This object function returns success (or failure) of C<combine()> or
  492. C<parse()>, whichever was called more recently.
  493.  
  494. =item error_input
  495.  
  496.  $bad_argument = $csv->error_input();
  497.  
  498. This object function returns the erroneous argument (if it exists) of
  499. C<combine()> or C<parse()>, whichever was called more recently.
  500.  
  501. =back
  502.  
  503. =head1 EXAMPLE
  504.  
  505.   require Text::CSV_XS;
  506.  
  507.   my $csv = Text::CSV_XS->new;
  508.  
  509.   my $column = '';
  510.   my $sample_input_string = '"I said, ""Hi!""",Yes,"",2.34,,"1.09"';
  511.   if ($csv->parse($sample_input_string)) {
  512.     my @field = $csv->fields;
  513.     my $count = 0;
  514.     for $column (@field) {
  515.       print ++$count, " => ", $column, "\n";
  516.     }
  517.     print "\n";
  518.   } else {
  519.     my $err = $csv->error_input;
  520.     print "parse() failed on argument: ", $err, "\n";
  521.   }
  522.  
  523.   my @sample_input_fields = ('You said, "Hello!"',
  524.                  5.67,
  525.                  'Surely',
  526.                  '',
  527.                  '3.14159');
  528.   if ($csv->combine(@sample_input_fields)) {
  529.     my $string = $csv->string;
  530.     print $string, "\n";
  531.   } else {
  532.     my $err = $csv->error_input;
  533.     print "combine() failed on argument: ", $err, "\n";
  534.   }
  535.  
  536. =head1 CAVEATS
  537.  
  538. This module is based upon a working definition of CSV format which may not be
  539. the most general.
  540.  
  541. =over 4
  542.  
  543. =item 1
  544.  
  545. Allowable characters within a CSV field include 0x09 (tab) and the inclusive
  546. range of 0x20 (space) through 0x7E (tilde). In binary mode all characters
  547. are accepted, at least in quoted fields:
  548.  
  549. =item 2
  550.  
  551. A field within CSV may be surrounded by double-quotes. (The quote char)
  552.  
  553. =item 3
  554.  
  555. A field within CSV must be surrounded by double-quotes to contain a comma.
  556. (The separator char)
  557.  
  558. =item 4
  559.  
  560. A field within CSV must be surrounded by double-quotes to contain an embedded
  561. double-quote, represented by a pair of consecutive double-quotes. In binary
  562. mode you may additionally use the sequence C<"0> for representation of a
  563. NUL byte.
  564.  
  565. =item 5
  566.  
  567. A CSV string may be terminated by 0x0A (line feed) or by 0x0D,0x0A
  568. (carriage return, line feed).
  569.  
  570. =head1 AUTHOR
  571.  
  572. Alan Citterman F<E<lt>alan@mfgrtl.comE<gt>> wrote the original Perl
  573. module. Please don't send mail concerning Text::CSV_XS to Alan, as
  574. he's not involved in the C part which is now the main part of the
  575. module.
  576.  
  577. Jochen Wiedmann F<E<lt>joe@ispsoft.deE<gt>> rewrote the encoding and
  578. decoding in C by implementing a simple finite-state machine and added
  579. the variable quote, escape and separator characters, the binary mode
  580. and the print and getline methods.
  581.  
  582. =head1 SEE ALSO
  583.  
  584. L<perl(1)>, L<IO::File(3)>, L<IO::Wrap(3)>
  585.  
  586. =cut
  587.