How to remove the Comma from the last occurrence [PERL]

Asked

Viewed 98 times

2

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

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

but I want only in the last instance to remain only the key without the comma first. thus:

{"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 "}";
  • https://stackoverflow.com/questions/2468999/how-can-i-split-a-perl-string-only-on-the-last-occurrence-of-the-separator

2 answers

1

Without recourse to regex, one can do the same by changing the order of the actions. The comma is added before each member from the second iteration.

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

print salvar "{";

my $addComma = 0;
while($file =~ m/"name":"(.*?)","price":(.*?),/ig) {
    my $name = $1;
    my $price = $2 / 100;

    print $name.":".$price."\n";
    print salvar ",\n" if ($addComma);
    print salvar '"'.$name.'":"'.$price.'"';
    $addComma = 1;
}

print salvar "}";

0


Use that regex.

(.*?)(,)(})

It will capture everything to the last comma that will be followed by the lock of keys }.

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

$1$3

Then the result will be:

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

You can test this regex here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.