I created such function, and it works. But I am asking: "is there a more elegant way of implementation?". The function recursively loops through the data structure, removes the empty elements and if there are no elements in the current node - returns 0; The algorithm for arrays and hashes is the same.
as the result the script will print:#!/usr/bin/perl -w use strict; use Data::Dumper; my @array = ( [1], [], {1 => 2, 2 =>{}} ); clean(\@array); print Dumper(\@array); sub clean { my $ref = shift; my $ref_name = ref($ref); if ($ref_name eq "SCALAR") { return 1; } elsif ($ref_name eq "ARRAY") { my $n = scalar(@$ref); for(my $i = 0; $i < $n; $i++) { my $result = clean($ref->[$i]); if ($result == 0) { delete($ref->[$i]); } } $n = scalar(@$ref); if ($n == 0) { return 0; } return 1; } elsif ($ref_name eq "HASH") { while(my ($key, $value) = each( %$ref)) { my $result = clean($value); if ($result == 0) { delete($ref->{$key}); } } my $n = scalar(keys %$ref); if ($n == 0) { return 0; } return 1; } elsif ($ref_name eq "REF") { die "incorrect reference submitted to function clean\n"; } else { clean(\$ref_name); } }
$VAR1 = [ [ 1 ], undef, { '1' => 2 } ];
In reply to Perl task function by usr345
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |