in reply to Trying to make the code more clear and clean
It's possible I missed some nuance but I think you can totally eliminate the temporary hash, and the if conditional if you just guard a single array-dereference point against definedness:
#!usr/bin/env perl use strict; use warnings; use List::Util 'uniq'; sub do_thing { my ($file_path, $href) = @_; open my $fh, '<', $file_path or return 0; while (my $line = <$fh>) { # stuff my $group = 'some setup for this line.'; my $value = 'some setup for this line.'; push @{$href->{test}}, { group => $group, values => [ $value, sort uniq(@{$href->{values} // []}), # This will be em +pty if the definedness test would have been false. ], }; } }
For me I like to ask myself if the temporary variable is adding clarity or not. In this case I didn't think it was, and in fact after removing it, it made it more clear to me that the if conditional was overkill. Instead of the conditional, we simply guard against $href->{values} not being defined. If it is undefined, we provide an empty array reference in @{$href->{values} // []}. The functions sort and uniq are not going to complain about being handed an empty list. And your conditional was really only dealing with the possibility that $href->{values} was undefined, or that the list was empty. We've handled both of those cases here.
If your code can be made to avoid conditional branches, it's usually going to be easier to follow. And often (but not always), temporary variables increase the amount of state that one has to keep in mind.
I am wondering, though, why $values isn't being passed through the uniq filter. Is it desired behavior to possibly add a duplicate but then filter it out later?
Update:
EDIT: I found out that it actually won't do what I need - it will not push the value in the same array of the group. Not sure how to fix it yet.
EDIT-2: I'm sorry if my question was not understandable. I though about it and from the comments I leraned that I need to clerify my question (sorry again). I have talked about the inner structure but actually the final structure which I need is:
Now the question really is hard to follow, and hard to answer.
Dave
|
|---|