#!/usr/bin/perl use strict; use warnings; # if first argument isnt a valid input file, die die("USAGE: $0 [input file]\n") if (! -f $ARGV[0]); # initialize some vars my $indent = my $sbrace = my $cbrace = 0; # slurp input file contents my $contents; { local $/ = undef; open(my $IN, '<', $ARGV[0]) or die("couldn't open file: $!"); $contents = <$IN>; close($IN); } # regex match every brace (with an optional trailing comma), evaluating replace as sub $contents =~ s/([\{\}[\],],?)/indent_brace($1)/egmsx; $contents =~ s/\n+/\n/g; # print out entire file to original filename plus '.out' open(my $OUT, '>', $ARGV[0].'.out') or die("couldn't open file: $!"); print {$OUT} $contents; close($OUT); # where the REAL work is done sub indent_brace { # split into array of chars my @match = split //, shift; # define it in local scope my $result; # decrement indent and appropriate brace count if($match[0] eq ']' || $match[0] eq '}') { $indent--; $sbrace-- if $match[0] eq ']'; $cbrace-- if $match[0] eq '}'; } # inject newlines and indenting tabs if($match[0] eq ',') { $result = join '', @match, "\n"; } else { $result = join '', "\n", "\t"x$indent, @match, "\n"; } # increment indent and appropriate brace count if($match[0] eq '[' || $match[0] eq '{') { $indent++; $sbrace++ if $match[0] eq '['; $cbrace++ if $match[0] eq '{'; } return $result; }