Skip to content

Instantly share code, notes, and snippets.

@ggl
Last active December 18, 2015 18:19
Show Gist options
  • Save ggl/5825108 to your computer and use it in GitHub Desktop.
Save ggl/5825108 to your computer and use it in GitHub Desktop.
Display a CSV file to STDOUT using Data::Dumper or YAML::Tiny
#!/usr/bin/env perl
#
# Display a CSV file to STDOUT using Data::Dumper or YAML::Tiny
use strict;
use warnings;
use Getopt::Std;
use Text::CSV;
use Data::Dumper;
$Data::Dumper::Terse = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Quotekeys = 0;
my %opt = (y => 0);
getopts('y', \%opt);
my %arg = (file => $ARGV[0]);
unless ($arg{file}) {
print "usage: $0 [-y] file.csv\n";
exit;
}
my $yt;
if ($opt{y}) {
require YAML::Tiny;
$yt = YAML::Tiny->new;
}
my $csv = Text::CSV->new ( { binary => 1 } )
or die "Cannot use CSV: ".Text::CSV->error_diag ();
open(my $fh, "<:encoding(utf8)", $arg{file})
or die "Cannot open file $arg{file}: $!";
$csv->column_names($csv->getline($fh));
while (my $row = $csv->getline_hr($fh)) {
if ($opt{y}) {
$yt->[0] = $row;
print($yt->write_string);
}
else {
print(Dumper($row));
}
}
$csv->eof or $csv->error_diag();
close $fh;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment