Simon. Simon. - 2 months ago 6
JSON Question

How to remove an object from an array in Perl

I have a JSON string strcutred like so:

[{"ip":"", "comment":""}, {"ip":"", "comment":""}]


I'm trying to figure out how to remove one of these objects by identification from the IP and/or comment keys.

The closest i've got so far is this:

my $jsn = decode_json('[{"ip":"1.2.3.4", "comment":"one"}, {"ip":"10.10.10.10","comment":"two"}]');

foreach(@{$jsn}){
if($_->{ip} eq '1.2.3.4'){
print "Found!";
splice @{$jsn}, $_, 1;
}
}


I know splice doesn't work in this example. If i could get the index of the object (ideally without a counter), i think i could then remove the correct object.

Answer

grep is your friend here. It creates a new list of elements in an existing list that match an expression.

my @filtered = grep { $_->{ip} ne '1.2.3.4' } @$jsn;