Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

added class-level overridable defaults

You can override in two places: first, when instantiating the object,
and then, when passing parameters to the read methods.
  • Loading branch information...
commit a85e75fc5e710fc521bbfd4e409959d90a95dca5 1 parent 524b3a2
@masak authored
Showing with 55 additions and 5 deletions.
  1. +7 −0 README
  2. +0 −3  TODO
  3. +30 −2 lib/Text/CSV.pm
  4. +18 −0 t/06-new.t
View
7 README
@@ -22,6 +22,13 @@ Oh, and the C<read> methods take the following named parameters:
is assumed to be a special header line, the values on that
line are used as hash keys, and :skip-header is suppressed.
+If you see yourself regularly contravening the defaults of one or more of
+these parameters, it might be a good idea to instantiate the Text::CSV
+class, giving it the default values you want:
+
+ my $reader = Text::CSV.new( :output<hashes>, :!strict );
+ my Hash[Str] @hashes = $reader.read-file('somefile.csv');
+
== License
This module is released under Artistic 2.0. See LICENSE.
View
3  TODO
@@ -1,4 +1 @@
-* Make all the flags into attributes of the Text::CSV class, and cause those
- attributes to work as the defaults to the C<read> methods.
-
* S26-Pod-document the module.
View
32 lib/Text/CSV.pm
@@ -11,13 +11,41 @@ grammar Text::CSV::File {
}
class Text::CSV {
+ has $!trim;
+ has $!strict;
+ has $!skip-header;
+ has $!output;
+
+ my $trim-default = False;
+ my $strict-default = 'default';
+ my $skip-header-default = False;
+ my $output-default = 'arrays';
+
sub extract_text($m, :$trim) {
my $text = ($m<quoted_contents> // $m).subst('""', '"', :global);
return $trim ?? $text.trim !! $text;
}
- method read($input, :$trim, :$output = 'arrays', :$skip-header,
- :$strict is copy = 'default') {
+ method read($input, :$trim is copy, :$strict is copy,
+ :$skip-header is copy, :$output is copy) {
+
+ if self.defined {
+ $trim //= $!trim // $trim-default;
+ $strict //= $!strict // $strict-default;
+ $skip-header //= $!skip-header // $skip-header-default;
+ if $output ~~ Failure {
+ $output = $!output // $output-default
+ }
+ }
+ else {
+ $trim //= $trim-default;
+ $strict //= $strict-default;
+ $skip-header //= $skip-header-default;
+ if $output ~~ Failure {
+ $output = $output-default;
+ }
+ }
+
Text::CSV::File.parse($input)
or die "Sorry, cannot parse";
my @lines = $<line>;
View
18 t/06-new.t
@@ -0,0 +1,18 @@
+use v6;
+use Test;
+
+use Text::CSV;
+
+my $input = q[[[one,two
+three,four,excess
+five]]];
+
+my Text::CSV $reader .= new( :output<hashes>, :!strict );
+is_deeply $reader.read($input),
+ [ { one => 'three', two => 'four' },
+ { one => 'five' } ],
+ 'the defaults are stored in attributes in the class';
+
+done_testing;
+
+# vim:ft=perl6
Please sign in to comment.
Something went wrong with that request. Please try again.