in reply to How can one delete an element and it corresponding values from the array of arrays?
Hello again, supriyoch_2008,
I totally agree with tobyink that a hash is the superior option here. But, if you insist on using a 2-dimensional array, here is how to code it:
#! perl use strict; use warnings; use Data::Dumper; my @sample1 = qw/ a b c d /; my @sample2 = qw/ 1 2 3 4 /; my @sample3 = qw/ x1 x2 x3 x4 /; my @big = (\@sample1, \@sample2, \@sample3); # <-- Note: use re +ferences here! print "Original big array:\n", Dumper(@big), "\n"; my $deleted_ele = 'x3'; remove(\@big, $deleted_ele); print "Resultant big array:\n", Dumper(@big), "\n"; print "Deleted element: $deleted_ele\n"; print "Modified sample1:\n", Dumper(@sample1), "\n"; print "Modified sample2:\n", Dumper(@sample2), "\n"; print "Modified sample3:\n", Dumper(@sample3); sub remove { my ($array, $to_delete) = @_; for my $i (0 .. @$array - 1) { for my $j (0 .. @{$array->[$i]} - 1) { if ($array->[$i][$j] eq $to_delete) { splice @$array[$_], $j, 1 for 0 .. @$array - 1; # < +-- Can't use delete here return; } } } }
Output:
18:05 >perl 579_SoPW.pl Original big array: $VAR1 = [ 'a', 'b', 'c', 'd' ]; $VAR2 = [ '1', '2', '3', '4' ]; $VAR3 = [ 'x1', 'x2', 'x3', 'x4' ]; Resultant big array: $VAR1 = [ 'a', 'b', 'd' ]; $VAR2 = [ '1', '2', '4' ]; $VAR3 = [ 'x1', 'x2', 'x4' ]; Deleted element: x3 Modified sample1: $VAR1 = 'a'; $VAR2 = 'b'; $VAR3 = 'd'; Modified sample2: $VAR1 = '1'; $VAR2 = '2'; $VAR3 = '4'; Modified sample3: $VAR1 = 'x1'; $VAR2 = 'x2'; $VAR3 = 'x4'; 18:05 >
Compare this code to the solution given by tobyink, and it should be obvious that a hash is the way to go!
Hope that helps,
Update: Added 2 comments to the code.
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How can one delete an element and it corresponding values from the array of arrays?
by supriyoch_2008 (Monk) on Mar 18, 2013 at 10:35 UTC | |
by Athanasius (Archbishop) on Mar 18, 2013 at 11:25 UTC | |
by supriyoch_2008 (Monk) on Mar 22, 2013 at 03:40 UTC |