Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: Returning arrays from a package (feature qw/refaliasing/;)

by LanX (Saint)
on Oct 02, 2019 at 00:15 UTC ( [id://11106935]=note: print w/replies, xml ) Need Help??


in reply to Re: Returning arrays from a package
in thread Returning arrays from a package

Please allow me to nitpick a bit and to advertise an experimental feature

> You cannot return multiple lists from a function in Perl

well the OP is trying to return multiple array-refs not lists, and the new'ish use feature qw/refaliasing/; allows these to be assigned to multiple @arrays. (see tst2())

use strict; use warnings; use Data::Dump qw/pp dd/; use feature qw/refaliasing/; no warnings "experimental::refaliasing"; sub tst { (\my %args) = @_; pp \%args; } tst({a=>1,b=>2}); sub tst2 { return [1..3],[4..7] } our (@a,@b); (\@a,\@b) = tst2(); pp \@b; pp \@a;

{ a => 1, b => 2 } [4 .. 7] [1, 2, 3]

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Replies are listed 'Best First'.
Re^3: Returning arrays from a package (feature qw/refaliasing/;)
by jcb (Parson) on Oct 02, 2019 at 01:08 UTC

    While we are nitpicking, I will note that the experimental refaliasing feature seems to just make references into lvalues, such that tst2 is actually returning a flat list of arrayrefs, rather than multiple lists. You still cannot return multiple lists in Perl. Oh, and did I mention it is an experimental feature? :-)

        Indeed, the OP's function does that, but OP attempts to accept them as multiple arrays at line 23: my (@overall, @electronics, @safety) = breakouts(@products)­;

        This mixing of metaphors needs to be fixed one way or the other, and I suggest that, since OP wants to export globals, the right way to fix it is to directly load the globals instead of creating lexicals to shadow them. I am surprised that perl does not warn about this; OP does use warnings;.

        This also leads to a third option, which is the C way of passing references to breakouts and having it populate the arrays passed as arguments, but I think the oft-seen quip "Keep It Simple, Stupid" applies here: breakouts is not some general function, but sorts specifically this data into these bins. A better architecture would involve replacing the whole thing with an SQL database (start with DBI and DBD::SQLite and move up to DBD::Pg when needed) but OP seems to want these arrays for some reason.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11106935]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (1)
As of 2024-04-25 00:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found