in reply to Trying to make the code more clear and clean

Hi, often you can skip a `defined` check to decide whether or not you can dereference something, without autovivifying it if it doesn't exist, by supplying a default. Note use of the defined-or operator //.

$ perl -MData::Dumper -Mstrict -wE 'my $foo = {}; say for @{ $foo->{ba +r} }; say Dumper $foo' $VAR1 = { 'bar' => [] };
$ perl -MData::Dumper -Mstrict -wE 'my $foo = {}; say for @{ $foo->{ba +r} // [] }; say Dumper $foo' $VAR1 = {};

This should work if I understand your partial code sample:

open(my $fh, '<', "$file_path") or return 0; my $href = {}; while (my $line = <$fh>) { # ........... # ........... # Additional operations of the lines of the file # ........... # ........... push @{ $href->{test} }, { group => $group, values => [ sort uniq $value, @{ $href->{values} // [] } ] +, }; }
(...although it seems a bit odd to have a top-level key with values that are then added to the sub-hashes. Could you build the combined list when you use the contents of $href?)

Hope this helps!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Trying to make the code more clear and clean
by ovedpo15 (Pilgrim) on Jul 29, 2019 at 22:16 UTC
    Thanks all for the replies! My question was not understandable enough so I have edited it. please take a look if you can, thanks, and sorry again!