Skip to content

Commit

Permalink
Normalized csv to work similar to yml and j.
Browse files Browse the repository at this point in the history
  • Loading branch information
Timofey Potapov committed Nov 5, 2024
1 parent 7c6e47d commit 3c48277
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
23 changes: 16 additions & 7 deletions lib/e.pm
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ CSV parser.
Syntax:
csv ( ARRAYREF_OF_ARRAYREFS )
csv ( ARRAYREF, [ARRAYREF] )
csv ( STRING )
csv ( )
Expand Down Expand Up @@ -943,36 +944,44 @@ sub import {
}

# Reference to string.
if ( ref( $thing ) eq "ARRAY" ) {
return join "\n",
map { $e::_csv->combine( @$_ ) && $e::_csv->string; } @args;
if ( ref( $thing ) ne "ARRAY" ) {
die "csv arguement is not an array reference!\n";
}

die "csv arguement is not an array reference!\n";
if ( ref( $thing->[0] ) ne "ARRAY" ) {
$thing = [@args];
}

join "\n",
map { $e::_csv->combine( @$_ ) && $e::_csv->string; } @$thing;

},

# Json.
j => sub {
if ( !$imported{$caller}{"Mojo::JSON"}++ ) {
require Mojo::JSON;
}
Mojo::JSON::j( @_ );
my @args = @_ ? @_ : ( $_ );
Mojo::JSON::j( @args );
},

# XML/HTML.
x => sub {
if ( !$imported{$caller}{"Mojo::DOM"}++ ) {
require Mojo::DOM;
}
Mojo::DOM->new( @_ );
my @args = @_ ? @_ : ( $_ );
Mojo::DOM->new( @args );
},

# YAML.
yml => sub {
if ( !$imported{$caller}{"YAML::XS"}++ ) {
require YAML::XS;
}
my ( $thing ) = @_;
my @args = @_ ? @_ : ( $_ );
my ( $thing ) = @args;
ref $thing
? YAML::XS::Dump( $thing )
: YAML::XS::Load( $thing );
Expand Down
10 changes: 10 additions & 0 deletions t/01-simple.t
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,21 @@ is
qq(A1,B1,C1),
"csv - ref to csv string (single)";

is
csv( [ [ "A1", "B1", "C1" ] ] ),
qq(A1,B1,C1),
"csv - ref to csv string (single, aoa)";

is
csv( [ "A1", "B1", "C1" ], [ "A2", "B2", "C2" ] ),
qq(A1,B1,C1\nA2,B2,C2),
"csv - ref to csv string (multiple)";

is
csv( [ [ "A1", "B1", "C1" ], [ "A2", "B2", "C2" ] ] ),
qq(A1,B1,C1\nA2,B2,C2),
"csv - ref to csv string (multiple, aoa)";

is
csv( [ "A1", "B1", "C1" ], [ "A2", "B2", "C\n2" ] ),
qq(A1,B1,C1\nA2,B2,"C\n2"),
Expand Down

0 comments on commit 3c48277

Please sign in to comment.