usr345 has asked for the wisdom of the Perl Monks concerning the following question:
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 } ];
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Perl task function
by BrowserUk (Patriarch) on Sep 08, 2010 at 21:25 UTC | |
|
Re: Perl task function
by ikegami (Patriarch) on Sep 08, 2010 at 22:49 UTC | |
by usr345 (Sexton) on Sep 09, 2010 at 09:58 UTC | |
by ikegami (Patriarch) on Sep 09, 2010 at 15:16 UTC | |
by BrowserUk (Patriarch) on Sep 09, 2010 at 15:25 UTC |