Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: references best practice (wantarray)

by lodin (Hermit)
on Apr 25, 2008 at 14:35 UTC ( #682839=note: print w/replies, xml ) Need Help??


in reply to references best practice

Regarding the first and last alternatives (returning a plain list or an array reference): there's a middle road here that you sometimes encounter. The routine can return a list in list context and an array reference in scalar context. That is, it usually looks like this:

sub foobar { ... return wantarray ? @foobar : \@foobar; }

Let's say foo always returns a plain array, bar always returns the array reference, and foobar is the middle road. Then you'll have

| foo | bar | foobar | "best" ------+-----------+----------+-------------+------------- List | foo() | @{bar()} | foobar() | foo / foobar Ref | [ foo() ] | bar() | foobar() | bar / foobar Count | foo() | @{bar()} | @{foobar()} | foo
and in terms of memory efficiency this translates to
| foo | bar | foobar ------+-----------+----------+-------- List | copy | copy | copy Ref | copy | no-copy | no-copy Count | no-copy | no-copy | no-copy
This sums up to foobar having a more convenient syntax than bar when memory isn't an issue, yet has the same memory efficiency.

However, when dealing with large lists and you only want the count/length, you can't in foobar use wantarray to make the sometimes very useful optimization (both speed- and memory-wise) of not fully processing all elements but just return the count. (For instance, your list may contain objects that then needn't be created.)

My conclusion is, as ever so often, that it depends, and it's almost always just a convenience decision. In the worst case you just create foo_ref or bar_count.

lodin

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2022-01-27 10:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (70 votes). Check out past polls.

    Notices?