Monday, June 20, 2011

How to delete an item in a perl array.

delete ($keys[$index] ) - does not really delete - it just sets it to
undef.


So, use splice - line 859 below .

Here, I have a list of 5 elements ( 866) , and I want to randomize it, so I
will call randomize_array () and this returns a randomized array.

839 sub randomize_array {
840
841 my @keys = @_;
842
843 my @new_array = ();
844
845 while ( 1 ) {
846
847
848 my $len = scalar ( @keys) ;
849
850 if ( $len == 0 ) { last; }
851
852 my $k= int rand( scalar(@keys));
853 #printf ( "rand is $k, value = $keys[$k] ");
854
855 push ( @new_array, $keys[$k] );
856
857 #delete ( $keys[$k] );
858
859 splice ( @keys, $k, 1 );
860
861 }
862 printf ("new array = [@new_array], size = %d\n", scalar
(@new_array));
863 return @new_array;
864 }
865
866 my @array = ( "5","10","15","25","35");
867
868 printf ( "old array = @array" );
869 printf ("\n");
870 printf ( scalar (@array) );
871
872 my @newarray = &randomize_array ( @array );
873
874 printf ( "new array = @newarray" );
875
876 " look at http://www.perlmonks.org/?node_id=1871"

No comments:

Post a Comment