in reply to When function is executed twice I get the results from the first set in the second

Your code doesn't run at all in fact. @array does not exist and your prototyped sub is declared too late for the prototype to be checked.

As already suggested use strictures (use strict; use warnings; - see The strictures, according to Seuss).

Don't use prototyped subs. In your sample code the prototype says "take no parameters" but @array is almost certainly intended to be a parameter (you surely aren't using global variables are you?).

A first cut at cleaning up the code could look like:

#!/usr/bin/perl use strict; use warnings; my @deck = qw(card1 card2 card3 card4); my @shuffle1 = shuffle (@deck); my @shuffle2 = shuffle (@shuffle1); print "@shuffle1\n"; print "@shuffle2\n"; sub shuffle { my $first = 0; my $last = $#_; my @newdeck; while ($first < $last) { push @newdeck, $_[$last--], $_[$first++]; } return @newdeck; }

Using a somewhat more Perlish (and probably harder to understand) approach to implementing shuffle may get you to:

sub shuffle { my @newdeck; push @newdeck, @_[-$_ - 1, $_] for 0 .. @_ / 2 - 1; return @newdeck; }

Both versions print:

card4 card1 card3 card2 card2 card4 card3 card1

True laziness is hard work
  • Comment on Re: When function is executed twice I get the results from the first set in the second
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: When function is executed twice I get the results from the first set in the second
by happy.barney (Friar) on Nov 16, 2009 at 07:13 UTC
    push @newdeck, pop, shift while @_;
    but every version fails in case of odd number of cards ...
    push @newdeck, grep defined, pop, shift while @_;