http://www.perlmonks.org?node_id=439495

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

Hello wise monks,

is any better (more elegant) way to do it:
my @array = qw/one two three/; my @out; push @out,"@array\n"; #push @out, reverse @array; <-- "threetwoone" push @out, "@{[reverse @array]}"; print @out;

thanks for yours wisdom,
Lukasz

Replies are listed 'Best First'.
Re: Push and list context
by Errto (Vicar) on Mar 14, 2005 at 23:34 UTC
    I'm not sure whether your main issue is print isn't adding spaces when you print a list, or that what you really want to do is push onto an array a string consisting of another list joined with spaces. If the latter, Mugatu is right. If the former, then you can do either
    push @out, reverse @array; print join " ", @out;
    or
    push @out, reverse @array; { local $, = " "; print @out; }
    Update: forgot the reverse
Re: Push and list context
by Mugatu (Monk) on Mar 14, 2005 at 23:28 UTC

    If I understand you correctly, this would be the preferred way:

    push @out, join " ", reverse @array;

    Or, to mimic the example more exactly:

    push @out, join $", reverse @array;
Re: Push and list context
by tlm (Prior) on Mar 15, 2005 at 02:37 UTC

    It's hard to say what better/more elegant would be in the absence of some context. That said, if all I wanted to do was to print an array forwards and backwards, with spaces between the elements, I'd just do something like

    my @array = qw(one two three); print "@{[@array, reverse @array]}\n";
    If you need to keep the reverse array, then
    my @yarra = reverse my @array = qw(one two three); print "@array @yarra\n";

    the lowliest monk

Re: Push and list context
by sh1tn (Priest) on Mar 14, 2005 at 23:49 UTC
    my @array = qw/one two three/; my @out = reverse @array; # or @out = (@out, reverse @array);


Re: Push and list context
by tphyahoo (Vicar) on Mar 15, 2005 at 11:56 UTC
    Putting arrays in quotes seems to be the same as joining them. That is, it adds spaces betweeen the elements. This works, and is real easy to read.
    use warnings; use strict; my @array = qw/one two three/; my @reversed = reverse @array; print "@array @reversed", "\n";
      Putting arrays in quotes seems to be the same as joining them. That is, it adds spaces betweeen the elements.

      Array interpolation uses $" as the separator, which defaults to a space, but can be changed to anything. Thus, "@array" is equivalent to join($", @array) (which I had in my earlier reply, but didn't really explain all the way).