BEGIN{ my %array_copy = (); sub elements(\@;$){ my $no_gc = $_[0]; # Hold onto $_[0] so it doesn't get garbage collected . $array_copy {$_[0]} = () unless defined $array_copy{$_[0]}; # Assign empty list if new. $_[1] = 1 unless $_[1] ; # Get one element if none specified. my @vals = splice(@{$_[0]}, 0, $_[1] ); # Pop elements. if (@vals){ # If elements to return push @{$array_copy{$_[0]}},@vals; # Push elements into temp copy. return @vals; # then return them. }else{ @$no_gc = @{$array_copy {$_[0]}}; # Array now restored. delete $array_copy{$_[0]}; # Free array copy return ; } } }