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

Brethren,

How do I pull out the n'th value when a function returns a list, without using an intermediate array variable? E.g. the following works, but by introducing the clutter of @temp;

use strict; sub dirs{qw(NORTH SOUTH EAST WEST)} my(@temp) = dirs(); my($horaceGreeleyDir) = $temp[3];
but the following attempts don't
my($horaceGreeleyDir) = dirs()[3]; my($horaceGreeleyDir) = @{dirs()}[3]; my($horaceGreeleyDir) = ${dirs()}[3]; my($horaceGreeleyDir) =()[3] = dirs();
This works, but is looks worse than the original:
(undef, undef, undef, my $horaceGreeleyDir) = dirs();
Suggestions?

throop

meta-question: on what should I have searched to answer this question myself?

Replies are listed 'Best First'.
Re: Pulling out an element from a function return without using an intermediate list
by ikegami (Patriarch) on Feb 19, 2007 at 21:42 UTC
Re: Pulling out an element from a function return without using an intermediate list
by rhesa (Vicar) on Feb 19, 2007 at 21:42 UTC
Re: Pulling out an element from a function return without using an intermediate list
by Joost (Canon) on Feb 19, 2007 at 21:43 UTC
      Really?
      use strict; my(undef, $aa, $bb) = dir(); Can't declare undef operator in my at (eval 159) line 2, near ") ="
        use strict; use warnings; my (undef, $param, undef, $other, @stuff) = dir(); print "undef, $param, undef, $other, @stuff"; sub dir { return (1, 2, 3, 4, 5, 6); }

        Prints:

        undef, 2, undef, 4, 5 6

        Works fine for me. What version of Perl are you using?


        DWIM is Perl's answer to Gödel

        On the other hand, the following versions all work:

        my $aa; my $bb; (undef, $aa, $bb) = dir();
        my ($aa, $bb); (undef, $aa, $bb) = dir();
        (undef, my $aa, my $bb) = dir();
        (undef, my ($aa, $bb)) = dir();
        my ($aa, $bb) = ( dir() )[1, 2];

        Update: Apparently, so does the following (contrary to the parent's claims):

        my (undef, $aa, $bb) = dir();

        Tested the last one on Perl 5.6.0, 5.6.1, 5.8.0 and 5.8.8.