ovedpo15 has asked for the wisdom of the Perl Monks concerning the following question:
I iterate over my data the perform the following code on each line:{ "test": [ { "group": "ABC1", "values": [ "abc", "xyz" ] }, { "group": "ABC2", "values": [ "abc2", ] }, { "group": "ABC3", "values": [ "xyz3" ] } ] }
I don't like how it looks, it is not clear and a bit mess.open(my $fh, '<', "$file_path") or return 0; while (my $line = <$fh>) { # ........... # ........... # Additional operations of the lines of the file # ........... # ........... my %a; # temp hash $a{"group"} = $group; if (defined($href->{"values"})) { $a{"values"} = [sort(uniq($value,@{$href->{"values"}}))]; } else { push(@{$a{"values"}},$value); } push(@{$href->{"test"}},\%a); }
I want to iterate though a file of data, parse it and extract group and values. The currect way I use:{ + "root": [ { "test": [ { "group": "XYZ", "values": [ "1234" ] }, { "group": "ABC", "values": [ "6.13.00" ] } ] }, { "test": [ { "group": "XYZ", "values": [ "tcsh" ] }, { "tool": "WEA", "values": [ "6.13.00" ] } ] }, { "test": [ { "group": "BAB", "values": [ "ASDAS", "12312321" ] }, { "group": "SADA", "values": [ "6.13.00", "1231231" ] } ] } ] }
It does what I need when there are no multiple values for the same group.sub parse_file { my ($file_path,$href) = @_; open(my $fh, '<', "$file_path") or return 0; while (my $line = <$fh>) { chomp($line); unless ($line =~ /\A[^,]+(?:,[^,]+){5}\z/) { next; } my ($key,$group,$value,$version,$file,$count) = split(/,/,$lin +e); push @{ $href->{test} }, { group => $group, values => [ sort uniq $value, @{ $href->{values} // [] } ] }; } close ($fh); return 1; } foreach my $dir (sort(@list_of_dirs)) { my ($all,%data); $all = $dir."/"."galish"; prase_results_raw($all,\%data); push(@all_data,\%data); }
If you take a look closely, you'll see duplicates of the same group name in the same test.{ + "root": [ { "test": [ { "group": "XYZ", "values": [ "1234" ] }, { "group": "ABC", "values": [ "6.13.00" ] } ] }, { "test": [ { "group": "XYZ", "values": [ "tcsh" ] }, { "tool": "WEA", "values": [ "6.13.00" ] } ] }, { "test": [ { "group": "BAB", "values": [ "ASDAS", ] }, { "group": "BAB", "values": [ "12312321" ] }, { "group": "SADA", "values": [ "6.13.00", ] } { "group": "SADA", "values": [ "1231231" ] } ] } ] }
|
|---|