Search code examples
perl

Perl - Array of Objects


Noob question here.

I'm sure the answer will be create objects, and store them in an array, but I want to see if there is an easier way.

In JSON notation I can create an array of objects like so:

[
  { width : 100, height : 50 },
  { width : 90, height : 30 },
  { width : 30, height : 10 }
]

Nice and simple. No arguing that.

I know Perl is not JS, but is there an easier way to duplicate an array of objects, then to create a new "class", new the objects, and push them in an array?

I guess what would make this possible is an object literal type notation that JS provides.

Or, is there another way to store two values, like above? I guess I could just have two arrays, each with scalar values, but that seems ugly...but much easier than creating a separate class, and all that crap. If I were writing Java or something, then no problem, but I don't want to be bothered with all that when I'm just writing a small script.


Solution

  • Here's a start. Each element of the @list array is a reference to a hash with keys "width" and "height".

    #!/usr/bin/perl
        
    use strict;
    use warnings;
        
    my @list = ( 
        { width => 100, height => 50 },
        { width => 90, height => 30 },
        { width => 30, height => 10 }
    );  
        
    foreach my $elem (@list) {
        print "width=$elem->{width}, height=$elem->{height}\n";
    }   
    

    And then you can add more elements to the array:

    push @list, { width => 40, height => 70 };