Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

on the fly reference to subroutine output

by ISAI student (Scribe)
on Mar 04, 2013 at 14:43 UTC ( [id://1021659]=perlquestion: print w/replies, xml ) Need Help??

ISAI student has asked for the wisdom of the Perl Monks concerning the following question:

Hello all. I have subroutine sub1 which outputs an array. I cannot alter that subroutine right now. Subroutine sub2, that needs expanding, uses it's output. The expansion requires that I pass a reference to the array/list output of sub1. Right now, I am using it like this:

sub2( sub1() ) ;
Iknow that it can be replaced by:
{ # minimal scope for @temp my @temp = sub1() ; sub2 ( \@temp ) ; } # end of local scope
Is there a way of not using 2 lines. instead of one I.E.
sub2( some_code( sub1() ) )
It's a matter of cooler code, not of true need.

Replies are listed 'Best First'.
Re: on the fly reference to subroutine output
by choroba (Cardinal) on Mar 04, 2013 at 14:51 UTC
    Use an anonymous array:
    sub2( [ sub1() ] );
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Just as a note - this beautiful solution works cause Perl flattens arrays.

      You can see that when you do:

      sub2( [ sub1(), (), () ] );
        Thank you all. It does the "magic".
        How does 'flattening' come into play when there's only one array? I would think 'unwiding' of an array is what takes place.

      This will make a copy of the array and give a reference to that, right? Is there a way to get a reference directly to the array passed back by sub1 with some assurance the copy won't happen? Or is this the sort of optimization that is up to the compiler (and may or may not happen?)?

      This example makes me think of rvalue references and move semantics in the new C++, where you can now return a std::vector, say, and be assured that the copy will really only grab the innards of the temporary returned rather than allocate anything new and copy things over. I wonder if there's something roughly equivalent in Perl (5 or 6).

        The incorrect assumption here is that sub1 is returning an array.

        In perl5, subs can return scalars or lists. Since it's not returning a (scalar) reference to an array, the only option is to store the list into a (possibly anonymous) array and pass a reference into sub2

        tjd

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1021659]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-03-19 02:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found