Perl - an array of objects

Noob question here.

I'm sure the answer will 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 such objects:

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

Nice and simple. Do not argue.

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

I suppose that would make it possible - this is a text entry of the type of object that JS provides.

Or is there another way to store two values, for example, higher? I guess I can only have two arrays, each with scalar values, but that seems ugly ... but much easier than creating a separate class and all that shit. If I were writing Java or something like that, then there would be no problem, but I do not want all this to bother when I just write a small script.

+6
source share
3 answers

Here begins. Each element of the @list array is a reference to a hash with the 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"; } 
+15
source

An array of hashes would do this, something like this

 my @file_attachments = ( {file => 'test1.zip', price => '10.00', desc => 'the 1st test'}, {file => 'test2.zip', price => '12.00', desc => 'the 2nd test'}, {file => 'test3.zip', price => '13.00', desc => 'the 3rd test'}, {file => 'test4.zip', price => '14.00', desc => 'the 4th test'} ); 

then refer to it as follows

 $file_attachments[0]{'file'} 

for more information check out this link http://htmlfixit.com/cgi-tutes/tutorial_Perl_Primer_013_Advanced_data_constructs_An_array_of_hashes.php

+3
source

Just like you do it in JSON, actually use JSON and Data :: Dumper to output the output from your JSON, which you can use in your Perl code:

 use strict; use warnings; use JSON; use Data::Dumper; # correct key to "key" my $json = <<'EOJSON'; [ { "width" : 100, "height" : 50 }, { "width" : 90, "height" : 30 }, { "width" : 30, "height" : 10 } ] EOJSON my $data = decode_json($json); print Data::Dumper->Dump([$data], ['*data']); 

which outputs

 @data = ( { 'width' => 100, 'height' => 50 }, { 'width' => 90, 'height' => 30 }, { 'width' => 30, 'height' => 10 } ); 

and all that is missing is my

+3
source

Source: https://habr.com/ru/post/894674/


All Articles