in reply to Returning arrays from a package
Hi, indeed you are close to something that works, but I recommend redesigning your solution to use Modern Perl, so that it not only works, but is extensible and maintainable.
Exporting globals when you just need to return some data is not usually the best design. Your case seems to call for an object class with methods that return the needed data (although really it seems like you want to build a spreadsheet; if so, there are tools for that). It's also usually better to pass around references to arrays; sooner or later you'll want to pass something else along with but separate from the array.
Here's one way using Moo to create a simple object class.
Output:package XYZ { use Moo; has [qw/_products overall electronics safety/] => ( is => 'lazy' ) +; sub _build__products { return [ ['MG-20',1,2,3], ['JU-54',2,3,1], ['HY-21',3,1,2], ['OK-34',4,10,5], ['GT-75',9,6,'n/a'], ['KJ-23',6,8,7], ['PO-65',7,5,10], ['HN-34',8,6,9], ['ED-23',9,7,4], ['FR-98',10,4,8], ]; } sub _build_overall { return [ map { join(':', @{ $_ }[1,0]) } @{ $_[0]->_products } + ]; } sub _build_electronics { return [ map { join(':', @{ $_ }[2,0]) } @{ $_[0]->_products } + ]; } sub _build_safety { return [ map { join(':', @{ $_ }[3,0]) } @{ $_[0]->_products } + ]; } }; use strict; use warnings; use feature 'say'; use XYZ; my $obj = XYZ->new; say 'OVERALL'; say for @{ $obj->overall }; say 'ELECTRONICS'; say for @{ $obj->electronics }; say 'SAFETY'; say for @{ $obj->safety }; __END__
(Note the need to provide a value for each column in your raw product data, to prevent warnings about uninitialized values.) <perl 11106931.pl OVERALL 1:MG-20 2:JU-54 3:HY-21 4:OK-34 9:GT-75 6:KJ-23 7:PO-65 8:HN-34 9:ED-23 10:FR-98 ELECTRONICS 2:MG-20 3:JU-54 1:HY-21 10:OK-34 6:GT-75 8:KJ-23 5:PO-65 6:HN-34 7:ED-23 4:FR-98 SAFETY 3:MG-20 1:JU-54 2:HY-21 5:OK-34 n/a:GT-75 7:KJ-23 10:PO-65 9:HN-34 4:ED-23 8:FR-98
Hope this helps!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Returning arrays from a package
by Anonymous Monk on Oct 02, 2019 at 11:11 UTC | |
by 1nickt (Canon) on Oct 02, 2019 at 12:14 UTC | |
by Anonymous Monk on Oct 04, 2019 at 01:42 UTC |