Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re^4: Memory utilization and hashes

by Cristoforo (Curate)
on Jan 27, 2018 at 20:24 UTC ( #1208000=note: print w/replies, xml ) Need Help??

in reply to Re^3: Memory utilization and hashes
in thread Memory utilization and hashes

The OP did update his data here.

A nit, but I think he wanted the anon array 'Answers' to be an array of hash refs.

He was concerned about creating a hash too large for memory. :-)
If the 'ids' were only 1 to 4, this wouldn't be a problem. But if the different 'ids' were in the thousands or so, I think that was what he what he wanted to avoid. You do reuse hash keys for this small example.

There was only 1 repeated id in his data, and this is where it is reused.

The test for 'exists' therefore tests true for this id only and output gets called. The rest of the output gets done outside the while loop (#remaining).

Your code outputs (on his revised data with my ($s1,$n,$s2,$v2,undef) = split ';',$_,5; changed to my (undef,$s1,$n,$s2,$v2) = split ';',$_,5;):

{"ip":["",""],"id":"2","host":""} {"ip":["",""],"id":"4","host":""} {"ip":[""],"id":"1","host":""} {"ip":[""],"id":"3","host":""} {"ip":[""],"id":"2","host":""}
I coded a similar solution to you (only difference being an array of hashrefs instead of values alone).
{"id":"1","Answer":[{"ip":""}],"host":""} {"id":"2","Answer":[{"ip":""},{"ip":""}],"host":"www.cnn"} {"id":"3","Answer":[{"ip":""}],"host":""} {"id":"4","Answer":[{"ip":""},{"ip":""}],"host":""} {"id":"2","Answer":[{"ip":""}],"host":""}
My solution was:
#!/usr/bin/perl use strict; use warnings; use JSON; open my $fh, '<', 'file2' or die $!; my %query; while (<$fh>) { chomp; my (undef, $cat, $id, undef, $val) = split /;/; if ($cat eq 'Query') { if (%query) { output(\%query); %query = (); } $query{$id} = [$val]; } else { push @{ $query{$id} }, {ip => $val}; } } output(\%query); sub output { my $query = shift; my ($id) = keys %$query; my $host = shift @{ $query->{$id} }; print encode_json({Answer => $query->{$id}, id => $id, host => $ho +st}),"\n"; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1208000]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2021-04-15 18:30 GMT
Find Nodes?
    Voting Booth?

    No recent polls found