I cannot decide which approach is more (1) idiomatic Perl, (2) efficient, or (3) "clear".
Let me explain by code. First, I can do
sub something {
...
$ref->{size} = 10;
$ref->{name} = "Foo";
$ref->{volume} = 100;
push (@references, $ref);
...
return @references;
}
or, I can do
sub something {
...
push (@names, "Foo");
$sizes{Foo} = 10;
$volumes{Foo} = 100;
...
return (\@names, \%sizes, \%volumes);
}
Both do essentially the same thing. The important thing is, I need the array, because I need to keep the order.
I know, there is always more than one way to do something, but still, which one of these two would you prefer?
Instead of thinking in meaningless terms such as something
, think and phrase the issue in concrete terms. In this case, you seem to be returning a list of objects that have name
, size
and volume
attributes. When you think of it that way, there is no reason to even consider the second method.
You can think of optimizations later if you run into problems, but even if you do, you would probably gain more from Memoize than by exploding data structures.
One efficiency improvement I will recommend is to return a reference from this subroutine:
sub get_objects {
my @ret;
while ( 'some condition' ) {
# should I return this one?
push @ret, {
name => 'Foo',
size => 10,
volume => 100,
};
}
return \@ret;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With