#!/usr/bin/perl -w use strict; BEGIN{ my %array_copy = (); # Storage of pristine arrays sub elements(\@;$){ my $no_gc = $_[0]; # Hold onto $_[0] so it doesn't get garbage collected . my @t = @{$_[0]}; # Temp array as I can't get it to assign to $array_copy directly. # ie $array_copy {$_[0]} = [ @{$_[0]} ] # Am I missing something? $array_copy {$_[0]} = [@t] unless defined $array_copy{$_[0]}; # Store if we haven't. my @temp = @{$array_copy {$_[0]}}; $_[1] = 1 unless $_[1] ; # Get one element if non specified. my @vals = splice(@{$_[0]}, 0, $_[1] ); # Pop elements. if (@vals){ # If elements to return return @vals; # then return them. }else{ # Time to restore array back to it's previous self. # Tried @$_[0] = @{$array_copy {$_[0]}} but wouldn't work. # Seemed to temporarily change the reference, only for this statement. @$no_gc = @{$array_copy {$_[0]}}; # Array now restored. delete $array_copy{$_[0]}; # Free array copy return ; } } } # The following is a silly example but it shows that calls to elements can be # nested. Also, passing an element count is optional, it will default to 1 element my @array1 = (1..15); my @array2 = (1..5); print "\@array1",join(", ", @array1),"\n"; print "\@array2",join(", ", @array2),"\n\n"; while (my @v = elements(@array1,3)){ print join(", ", @v),"\n"; print "-" x 30,"\n"; # Removal of elements from @array are visible here. while (my @x = elements(@array2,@array1) ){ # As this demonstrates. print "\t",join(", ", @x),"\n"; print "\t","_" x 30,"\n"; } } print "\@array1",join(", ", @array1),"\n"; print "\@array2",join(", ", @array2),"\n";