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

Why doesn't this work? Returns empty set. Pass by reference?

sub rev_array(@) { my @one = @_; my $length = @one; print "Length: $length\n"; my @two = (); while (my $entry = pop @one) { push @two, $entry; print "Push It!\n"; } return @two; }
Shine On, Pearte

Replies are listed 'Best First'.
Re: Reversing an array. Subroutine.
by ikegami (Patriarch) on Jan 11, 2007 at 22:37 UTC

    That won't work when one of the elements is 0, "", "0", undef, etc. Check the size of @one, not whether $entry is true or false.

    while (@one) { push(@two, pop(@one)); }

    Of course, using reverse would be even better.

    .oO( Why doesn't pop return an empty list for an empty array, allowing while (my ($item) = pop(@array))? )

    Update: For fun, a few ways to reverse a list:

    my @b = reverse(@a); my @b = sub { my @rv; push(@rv, pop()) while @_; return @rv }->(@a); my @b = sub { my @rv; unshift(@rv, shift()) while @_; return @rv }->(@ +a); my @b = map { $a[-$_] } reverse 0..$#a; my @b = map { $a[-$_] } -$#a..0; my @b = map { $a[$_] } sort { $b <=> @a } 0..$#a; my @b = map { $a[$_] } sub { my @rv; push(@rv, pop()) while @_; return + @rv }->(0..$#a); my @b = map { $a[$_] } sub { my @rv; unshift(@rv, shift()) while @_; r +eturn @rv }->(0..$#a); my @b = @a[ reverse 0..$#a ]; my @b = @a[ map { -$_ } -$#a..0 ]; my @b = @a[ sort { $b <=> @a } 0..$#a ]; my @b = @a[ sub { my @rv; push(@rv, pop()) while @_; return @rv }->(0. +.$#a) ]; my @b = @a[ sub { my @rv; unshift(@rv, shift()) while @_; return @rv } +->(0..$#a) ];

    I keep thinking of more, such as a counting loop...

Re: Reversing an array. Subroutine.
by jettero (Monsignor) on Jan 11, 2007 at 22:30 UTC
    That should indeed work. @rev = reverse @a might be better and/or faster... no comment. But your function appears to work to me. Show me the code where it doesn't work and I may have additional guesses.

    -Paul

Re: Reversing an array. Subroutine.
by Errto (Vicar) on Jan 11, 2007 at 22:29 UTC
    It works for me:
    my @array = (1,2,3,4,5); print rev_array @array;
    prints "54321".