How to get the last occurrence of Virgula [PERL]

2

Well I have a perl script that formats a json by leaving it in this format:

{"nome1":"123","nome2":"123","nome3":"123",}

But I want only the last occurrence to be just the key without the comma before. like this:

{"nome1":"123","nome2":"123","nome3":"123"}

Code:

   open(FILEHANDLE, '<', 'prices.json');
   my $file = <FILEHANDLE>;
   close(FILEHANDLE);
   open(salvar,'>>','730.json');
print salvar "{";

while($file =~ m/"name":"(.*?)","price":(.*?),/ig) {

my $name = $1;

my $price = $2 / 100;


print $name.":".$price."\n";
print salvar '"'.$name.'":"'.$price.'"'.",\n";
 }

print salvar "}";
    
asked by anonymous 18.09.2017 / 16:56

1 answer

0

Use this regex.

(.*?)(,)(})

It will capture everything up to the last comma which will be followed by the closing of } keys.

After this, just make a replace with capture groups 1 and 3.
To use the content captured by these groups just reference them this way:

$1$3

Then the result will be:

{"nome1":"123","nome2":"123","nome3":"123"}

You can test this regex here

    
18.09.2017 / 20:58