my $l; # all these three variables should probably better declared within the my @vals; # while loop. Only %pairs probably need to be declared before the while my $json; while (<>) { $l = $_; chomp $l; @vals = split /;/, $l; if ($vals[0] =~ /Query/) { $pairs{$vals[1]}{$vals[2]} = $vals[3]; # %pairs isn't declared anywhere } elsif {$vals[0] =~ /Answer/) { # syntax error: elsif { should be elsif ( $pairs{$vals[1}{$vals[2]} = $vals[3]; $json = encode_json $pairs{$vals[1]}; # what do you think is the content of $pairs{$vals[1]}? Probably not what you want to encode. print $json."\n"; delete $pairs{$vals[1]}; } }