Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better in Perl: an array of hash references or list of "flat" hashes?

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?

like image 242
Karel Bílek Avatar asked Dec 03 '22 14:12

Karel Bílek


1 Answers

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;
}
like image 153
Sinan Ünür Avatar answered May 07 '23 21:05

Sinan Ünür