On 06/29/2016 06:03 AM, Eric de Hont wrote:
Op 29-06-16 om 06:35 schreef Danny Wong:
Hi Perl GURUs,
I have a json file that needs parsing.

Here is a typical string I’m searching for. I want to delete everything but the last 2 character “],”.

        ],

        [

          "ansible",

          "2.1.0.0-1ppa~trusty",

          false

        ],


Here is what I tried:


I slurp the whole file into a variable.

my $SAVE = $/;

my $WHOLE_JSON_FILE = `cat ${JSON_FILE}`;

$/ = $SAVE;


while($WHOLE_JSON_FILE !~ /.*?(\s+\]\,\s+\[\s+\"ansible\".*?)\]\,?/gs)

{

   print "\$1 is $1";

}


The print statement is printing out the “matching string” but how do I remove that section of string from the slurp $WHOLE_JSON_FILE variable which contains the entire file content?



Hi Danny,

JSON is a strictly defined data format. Modifying such a file with regular expressions will sooner or later break the structure of your config file in a nasty way. The same goes for XML, HTML en the like. Therefore the real guru's have created modules to help us keep these files sane.


sub slurp_file {
    my $file = shift;
    local $/;
    open my $fh, '<', $file or die "Can't open $_: $!\n";

$_ is not set anywhere. you likely meant to use $file
<$fh>;
}

sub write_file {
    my $file = shift;
    open my $fh, '>', $file or die "Can't open $_: $!\n";

same bug.
print $fh @_ ;
}

since you are correct about modules being already there, why do you write your own versions of slurp_file and write_file? the module File::Slurp has those functions which are stable, fast and debugged.

uri

Reply via email to