| 1 | #!/usr/bin/env perl | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use utf8; | ||
| 7 | |||
| 8 | our $VERSION = '0.10'; | ||
| 9 | |||
| 10 | binmode STDERR, ':encoding(UTF-8)'; | ||
| 11 | binmode STDOUT, ':encoding(UTF-8)'; | ||
| 12 | binmode STDIN, ':encoding(UTF-8)'; | ||
| 13 | |||
| 14 | use Getopt::Long qw(:config no_ignore_case); | ||
| 15 | |||
| 16 | use Config::JSON::Enhanced; | ||
| 17 | use Data::Roundtrip qw/perl2yaml no-unicode-escape-permanently/; | ||
| 18 | |||
| 19 | my $OUTPUT_FILE = undef; | ||
| 20 | my %params = ( | ||
| 21 | 'commentstyle' => 'custom(</*)(*/>)', | ||
| 22 | 'tags' => ['<%', '%>'], | ||
| 23 | ); | ||
| 24 | |||
| 25 | sub usage { return | ||
| 26 | "Usage : $0 [--I inputstring] [--i 'afile.json'] [--o afile] [--c commentstyle] [--tags tags]\n" | ||
| 27 | ."\nIt will read a JSON string from command line (-I), or from a file (-i)\n" | ||
| 28 | ."\nor from STDIN (beware 4K limit on linux terminal, see CAVEATS for workaround).\n" | ||
| 29 | ."It will print its contents as a Perl variable (dump) to STDOUT or to a file (--o).\n" | ||
| 30 | ."It can escape/un-escape unicode characters (--escape-unicode) and/or --terse and/or --indent.\n" | ||
| 31 | } | ||
| 32 | if( ! Getopt::Long::GetOptions( | ||
| 33 | 'i=s' => \$params{'filename'}, | ||
| 34 | 'I=s' => sub { $params{'string'} = Encode::decode_utf8($_[1]) }, | ||
| 35 | 'o=s' => \$OUTPUT_FILE, | ||
| 36 | 'commentstyle|c=s' => \$params{'commentstyle'}, | ||
| 37 | 'tags|t=s' => \$params{'tags'}, | ||
| 38 | ) ){ die usage() } | ||
| 39 | |||
| 40 | if( ! exists($params{'filename'}) && ! exists($params{'string'}) ){ | ||
| 41 | # read from STDIN | ||
| 42 | $params{'string'} = do { local $/; <STDIN> } | ||
| 43 | } | ||
| 44 | |||
| 45 | my $result = Config::JSON::Enhanced::config2perl(\%params); | ||
| 46 | if( ! defined $result ){ print STDERR "$0 : error, call to ".'Config::JSON::Enhanced::config2perl()'." has failed.\n"; exit(1) } | ||
| 47 | |||
| 48 | if( defined $OUTPUT_FILE ){ | ||
| 49 | my $FH; | ||
| 50 | if( ! open($FH, '>', $$OUTPUT_FILE) ){ | ||
| 51 | print STDERR "$0 : error, failed to open output file '$OUTPUT_FILE', $!\n"; | ||
| 52 | print STDOUT perl2yaml($result); | ||
| 53 | } else { | ||
| 54 | print $FH perl2yaml($result); | ||
| 55 | close $FH; | ||
| 56 | } | ||
| 57 | } else { | ||
| 58 | print STDOUT perl2yaml($result); | ||
| 59 | } | ||
| 60 | 1; | ||
| 61 | __END__ |