#!perl use strict; use warnings; use JSON; my %host = (); while () { chomp; my @f = split /;/, $_; if ($f[0] eq 'Query') { $host{$f[1]} = $f[3]; } elsif ($f[0] eq 'Answer') { my $json = encode_json { host=>$host{$f[1]},$f[2]=>$f[3] }; print $json."\n"; delete $host{$f[1]}; } } __DATA__ Query;1;host;www.example.com Answer;1;ip;1.2.3.4 Query;2;host;www.cnn.com Query;3;host;www.google.com Answer;2;ip;2.3.4.5 Answer;3;ip;3.4.5.6