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

sub main { &first; &second; } sub first { some stuff.... return @something; } sub second { I need @something }
How would I pass @something to sub second? When would I use the @_ ?

Replies are listed 'Best First'.
Re: Using return values in subroutines
by merlyn (Sage) on Mar 27, 2006 at 00:35 UTC
Re: Using return values in subroutines
by sk (Curate) on Mar 27, 2006 at 00:37 UTC
    #/usr/local/bin/perl use strict; use warnings; main(); sub main { second(first()); } sub first { my @ret = qw (from first sub); return (@ret); } sub second { print "Message from first sub: " , join (' ', @_), $/; }

    output

    Message from first sub: from first sub

    Btw, you don't need the & to call the sub.

    cheers

    SK

Re: Using return values in subroutines
by zer (Deacon) on Mar 27, 2006 at 00:38 UTC
    sub first{ some stuff return @somearray } sub second{ my @Something = @_; #then do whatever } sub main{ second(first); } main;
    You dont really need to set a main routine. and y are you calling the subroutines as if it was a typeglob? You do not need the & prefix
Re: Using return values in subroutines
by GrandFather (Saint) on Mar 27, 2006 at 00:41 UTC

    Just use first as the parameter to second:

    use strict; use warnings; second (first ()); sub first { my @something = qw'apple monkey banana horse'; return @something; } sub second { print "@_"; }

    Prints:

    apple monkey banana horse

    Note that the &sub calling syntax is generally frowned on unless you really want to use it to pass the @_ for the current sub into the called sub.


    DWIM is Perl's answer to Gödel
Re: Using return values in subroutines
by blogical (Pilgrim) on Mar 27, 2006 at 01:42 UTC
    In case any of the previous, more efficient solution(s?), while accurate, didn't quite hit the spot:
    sub main { my @returned = &first; &second(@returned); #The & isn't necessary if perl already knows that first #and second are subroutines, i.e. if you declare them #prior to use as in the previous examples. } sub first { my @something = (qw[some stuff....]); return @something; } sub second { my @needs = @_; #@needs = something }
    One step better than passing out an array is passing a reference to the array. Both of these options let you manipulate the returned values in your main, which second(first()) won't. That's probably the main reason for not nesting them. The only other reason I can think of would be to
    disambiguate($a, @really, $long[3], {and => 'potentially', rather => \ +%confusing} &call( 'that', &is(\$already, $crowded)), $got_it{?})
    OC,TMTOWTDI ;)

    "One is enough. If you are acquainted with the principle, what do you care for the myriad instances and applications?"
    - Henry David Thoreau, Walden